repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarWatchExpressionsPane.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarWatchExpressionsPane.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.util.Elements; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * Watch expressions pane in the debugging sidebar. * */ public class DebuggingSidebarWatchExpressionsPane extends UiComponent< DebuggingSidebarWatchExpressionsPane.View> { public interface Css extends CssResource { String root(); String button(); String plusButton(); String refreshButton(); } interface Resources extends ClientBundle, RemoteObjectTree.Resources { @Source("DebuggingSidebarWatchExpressionsPane.css") Css workspaceEditorDebuggingSidebarWatchExpressionsPaneCss(); @Source("plusButton.png") ImageResource plusButton(); @Source("refreshButton.png") ImageResource refreshButton(); } /** * Listener of this pane's events. */ interface Listener { void onBeforeAddWatchExpression(); void onWatchExpressionsCountChange(); } /** * The view for the pane. */ static class View extends CompositeView<ViewEvents> { private final Resources resources; private final Css css; private final RemoteObjectTree.View treeView; private final Element plusButton; private final Element refreshButton; View(Resources resources) { this.resources = resources; css = resources.workspaceEditorDebuggingSidebarWatchExpressionsPaneCss(); treeView = new RemoteObjectTree.View(resources); plusButton = Elements.createDivElement(css.button(), css.plusButton()); refreshButton = Elements.createDivElement(css.button(), css.refreshButton()); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(treeView.getElement()); setElement(rootElement); attachButtonListeners(); } private void attachButtonListeners() { plusButton.addEventListener(Event.CLICK, new EventListener() { @Override public void handleEvent(Event evt) { getDelegate().onAddNewExpression(); evt.stopPropagation(); } }, false); refreshButton.addEventListener(Event.CLICK, new EventListener() { @Override public void handleEvent(Event evt) { getDelegate().onWatchRefresh(); evt.stopPropagation(); } }, false); } private void attachControlButtons(Element controlButtonsRoot) { controlButtonsRoot.appendChild(refreshButton); controlButtonsRoot.appendChild(plusButton); } } /** * The view events. */ private interface ViewEvents { void onAddNewExpression(); void onWatchRefresh(); } static DebuggingSidebarWatchExpressionsPane create(View view, DebuggerState debuggerState) { RemoteObjectTree tree = RemoteObjectTree.create(view.treeView, view.resources, debuggerState); return new DebuggingSidebarWatchExpressionsPane(view, tree); } private final RemoteObjectTree tree; private Listener delegateListener; private final RemoteObjectTree.Listener remoteObjectTreeListener = new RemoteObjectTree.Listener() { @Override public void onRootChildrenChanged() { if (delegateListener != null) { delegateListener.onWatchExpressionsCountChange(); } } }; private final class ViewEventsImpl implements ViewEvents { @Override public void onAddNewExpression() { if (delegateListener != null) { delegateListener.onBeforeAddWatchExpression(); } tree.collapseRootChildren(); tree.addMutableRootChild(); } @Override public void onWatchRefresh() { refreshWatchExpressions(); } } @VisibleForTesting DebuggingSidebarWatchExpressionsPane(View view, RemoteObjectTree tree) { super(view); this.tree = tree; tree.setListener(remoteObjectTreeListener); view.setDelegate(new ViewEventsImpl()); } void setListener(Listener listener) { delegateListener = listener; } void attachControlButtons(Element controlButtonsRoot) { getView().attachControlButtons(controlButtonsRoot); } void refreshWatchExpressions() { tree.reevaluateRootChildren(); } int getExpressionsCount() { return tree.getRootChildrenCount(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggerApiUtils.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggerApiUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import javax.annotation.Nullable; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectId; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectSubType; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectType; import com.google.collide.json.client.Jso; import com.google.collide.shared.util.StringUtils; import com.google.common.base.Objects; /** * Utility helper class that contains browser independent methods on the * Debugger API. * */ class DebuggerApiUtils { /** * Casts a {@link RemoteObject} to a boolean value. * * @param remoteObject the remote object to cast * @return boolean value */ public static boolean castToBoolean(@Nullable RemoteObject remoteObject) { if (remoteObject == null || remoteObject.getType() == null) { return false; } switch (remoteObject.getType()) { case BOOLEAN: return "true".equals(remoteObject.getDescription()); case FUNCTION: return true; case NUMBER: if (isNonFiniteNumber(remoteObject)) { return !"NaN".equals(remoteObject.getDescription()); } else { return !StringUtils.isNullOrEmpty(remoteObject.getDescription()) && Double.parseDouble(remoteObject.getDescription()) != 0; } case OBJECT: return remoteObject.getSubType() != RemoteObjectSubType.NULL; case STRING: return !StringUtils.isNullOrEmpty(remoteObject.getDescription()); case UNDEFINED: return false; default: return false; } } /** * Adds a new field to a {@link Jso} object from a primitive * {@link RemoteObject}. * * <p>NOTE: Non finite numbers will not be added! * * @param jso object to add the new value to * @param key key name * @param remoteObject primitive remote object to extract the value from * @return true if the field was added successfully, false otherwise (for * example, if the {@code remoteObject} did not represent a primitive * value) */ public static boolean addPrimitiveJsoField(Jso jso, String key, RemoteObject remoteObject) { if (remoteObject == null || remoteObject.getType() == null) { return false; } switch (remoteObject.getType()) { case BOOLEAN: jso.addField(key, "true".equals(remoteObject.getDescription())); return true; case FUNCTION: return false; case NUMBER: if (!isNonFiniteNumber(remoteObject)) { jso.addField(key, Double.parseDouble(remoteObject.getDescription())); return true; } return false; case OBJECT: if (remoteObject.getSubType() == RemoteObjectSubType.NULL) { jso.addNullField(key); return true; } return false; case STRING: jso.addField(key, remoteObject.getDescription()); return true; case UNDEFINED: jso.addUndefinedField(key); return true; default: return false; } } /** * Checks whether the given {@link RemoteObject}s are equal. * * @param a first remote object * @param b second remote object * @return true if both of the arguments point to the same remote object in * the Debugger VM, or if they are both {@code null}s */ public static boolean equal(@Nullable RemoteObject a, @Nullable RemoteObject b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return Objects.equal(a.getDescription(), b.getDescription()) && Objects.equal(a.hasChildren(), b.hasChildren()) && Objects.equal(a.getObjectId(), b.getObjectId()) && Objects.equal(a.getType(), b.getType()) && Objects.equal(a.getSubType(), b.getSubType()); } /** * Checks whether a given {@link RemoteObject} represents a non finite number * ({@code NaN}, {@code Infinity} or {@code -Infinity}). * * @param remoteObject the object to check * @return true if the remote object represents a non finite number */ public static boolean isNonFiniteNumber(RemoteObject remoteObject) { if (remoteObject.getType() != RemoteObjectType.NUMBER) { return false; } String description = remoteObject.getDescription(); return "NaN".equals(description) || "Infinity".equals(description) || "-Infinity".equals(description); } public static RemoteObject createRemoteObject(final String value) { return new RemoteObject() { @Override public String getDescription() { return value; } @Override public boolean hasChildren() { return false; } @Override public RemoteObjectId getObjectId() { return null; } @Override public RemoteObjectType getType() { return RemoteObjectType.STRING; } @Override public RemoteObjectSubType getSubType() { return null; } }; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/ConsoleView.java
client/src/main/java/com/google/collide/client/code/debugging/ConsoleView.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.code.debugging.DebuggerApiTypes.ConsoleMessage; import com.google.collide.client.code.debugging.DebuggerApiTypes.ConsoleMessageLevel; import com.google.collide.client.code.debugging.DebuggerApiTypes.ConsoleMessageType; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectSubType; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectType; import com.google.collide.client.code.debugging.DebuggerApiTypes.StackTraceItem; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.json.client.JsoArray; 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.collide.shared.util.StringUtils; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; import elemental.html.AnchorElement; /** * Console View. * */ public class ConsoleView extends UiComponent<ConsoleView.View> { public interface Css extends CssResource { String root(); String consoleMessages(); String messageRoot(); String messageLink(); String repeatCountBubble(); String consoleObject(); String consolePrimitiveValue(); String consoleDebugLevel(); String consoleErrorLevel(); String consoleLogLevel(); String consoleTipLevel(); String consoleWarningLevel(); String consoleStackTrace(); String consoleStackTraceCollapsed(); String consoleStackTraceExpanded(); String consoleStackTraceController(); String consoleStackTraceItem(); } interface Resources extends ClientBundle, RemoteObjectTree.Resources, RemoteObjectNodeRenderer.Resources { @Source("ConsoleView.css") Css workspaceEditorConsoleViewCss(); @Source("errorIcon.png") ImageResource errorIcon(); @Source("warningIcon.png") ImageResource warningIcon(); @Source("triangleRight.png") ImageResource triangleRight(); @Source("triangleDown.png") ImageResource triangleDown(); } /** * Listener of this pane's events. */ interface Listener { void onLocationLinkClick(String url, int lineNumber); } /** * The view for the sidebar call stack pane. */ static class View extends CompositeView<ViewEvents> { private final Css css; private final Resources resources; private final RemoteObjectNodeRenderer nodeRenderer; private final JsonArray<RemoteObjectTree> remoteObjectTrees = JsonCollections.createArray(); private final Element consoleMessages; private final EventListener clickListener = new EventListener() { @Override public void handleEvent(Event evt) { Element target = (Element) evt.getTarget(); if (target.hasClassName(css.messageLink())) { evt.preventDefault(); evt.stopPropagation(); AnchorElement anchor = (AnchorElement) target; int lineNumber = 0; String anchorText = anchor.getTextContent(); int pos = anchorText.lastIndexOf(':'); if (pos != -1) { try { lineNumber = (int) Double.parseDouble(anchorText.substring(pos + 1)); // Safe convert from one-based number to zero-based. lineNumber = Math.max(0, lineNumber - 1); } catch (NumberFormatException e) { // Ignore. } } getDelegate().onLocationLinkClick(anchor.getHref(), lineNumber); } else if (target.hasClassName(css.consoleStackTraceController())) { Element messageRoot = CssUtils.getAncestorOrSelfWithClassName(target, css.messageRoot()); if (messageRoot != null) { boolean expanded = messageRoot.hasClassName(css.consoleStackTraceExpanded()); CssUtils.setClassNameEnabled(messageRoot, css.consoleStackTraceExpanded(), !expanded); CssUtils.setClassNameEnabled(messageRoot, css.consoleStackTraceCollapsed(), expanded); } } } }; View(Resources resources) { this.resources = resources; css = resources.workspaceEditorConsoleViewCss(); nodeRenderer = new RemoteObjectNodeRenderer(resources); consoleMessages = Elements.createDivElement(css.consoleMessages()); consoleMessages.addEventListener(Event.CLICK, clickListener, false); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(consoleMessages); setElement(rootElement); } private void appendConsoleMessage(ConsoleMessage message, DebuggerState debuggerState) { boolean forceObjectFormat = false; JsonArray<RemoteObject> parameters; if (message.getType() != null) { switch (message.getType()) { case TRACE: // Discard all parameters. parameters = JsoArray.from(DebuggerApiUtils.createRemoteObject("console.trace()")); break; case ASSERT: parameters = JsoArray.from(DebuggerApiUtils.createRemoteObject("Assertion failed:")); parameters.addAll(message.getParameters()); break; case DIR: case DIRXML: // Use only first parameter, if any. parameters = message.getParameters().size() > 0 ? message.getParameters().slice(0, 1) : JsoArray.from(DebuggerApiTypes.UNDEFINED_REMOTE_OBJECT); forceObjectFormat = true; break; case ENDGROUP: // TODO: Support console.group*() some day. // Until then, just ignore the console.groupEnd(). return; default: parameters = message.getParameters(); break; } } else { parameters = message.getParameters(); } if (parameters.size() == 0) { if (StringUtils.isNullOrEmpty(message.getText())) { parameters = JsoArray.from(DebuggerApiTypes.UNDEFINED_REMOTE_OBJECT); } else { parameters = JsoArray.from(DebuggerApiUtils.createRemoteObject(message.getText())); } } Element messageElement = Elements.createDivElement(css.messageRoot()); // Add message link first. JsonArray<StackTraceItem> stackTrace = message.getStackTrace(); StackTraceItem topFrame = stackTrace.isEmpty() ? null : stackTrace.get(0); if (topFrame != null && !StringUtils.isNullOrEmpty(topFrame.getUrl())) { messageElement.appendChild(formatLocationLink( topFrame.getUrl(), topFrame.getLineNumber(), topFrame.getColumnNumber())); } else if (!StringUtils.isNullOrEmpty(message.getUrl())) { messageElement.appendChild(formatLocationLink( message.getUrl(), message.getLineNumber(), 0)); } // Add the Stack Trace expand/collapse controller. final boolean shouldDisplayStackTrace = !stackTrace.isEmpty() && (message.getType() == ConsoleMessageType.TRACE || message.getLevel() == ConsoleMessageLevel.ERROR); if (shouldDisplayStackTrace) { if (ConsoleMessageType.TRACE.equals(message.getType())) { messageElement.addClassName(css.consoleStackTraceExpanded()); } else { messageElement.addClassName(css.consoleStackTraceCollapsed()); } messageElement.appendChild(Elements.createSpanElement(css.consoleStackTraceController())); } // Add all message arguments. for (int i = 0, n = parameters.size(); i < n; ++i) { if (i > 0) { messageElement.appendChild(Elements.createTextNode(" ")); } messageElement.appendChild( formatRemoteObjectInConsole(parameters.get(i), debuggerState, forceObjectFormat)); } if (message.getLevel() != null) { switch (message.getLevel()) { case DEBUG: messageElement.addClassName(css.consoleDebugLevel()); break; case ERROR: messageElement.addClassName(css.consoleErrorLevel()); break; case LOG: messageElement.addClassName(css.consoleLogLevel()); break; case TIP: messageElement.addClassName(css.consoleTipLevel()); break; case WARNING: messageElement.addClassName(css.consoleWarningLevel()); break; } } if (shouldDisplayStackTrace) { messageElement.appendChild(formatStackTrace(stackTrace)); } updateConsoleMessageCount(messageElement, message.getRepeatCount()); consoleMessages.appendChild(messageElement); } private void updateLastConsoleMessageCount(int repeatCount) { Element messageElement = (Element) consoleMessages.getLastChild(); if (messageElement == null) { return; } updateConsoleMessageCount(messageElement, repeatCount); } private void updateConsoleMessageCount(Element messageElement, int repeatCount) { Element repeatCountElement = DomUtils.getFirstElementByClassName( messageElement, css.repeatCountBubble()); if (repeatCountElement == null) { if (repeatCount > 1) { repeatCountElement = Elements.createSpanElement(css.repeatCountBubble()); repeatCountElement.setTextContent(Integer.toString(repeatCount)); messageElement.insertBefore(repeatCountElement, messageElement.getFirstChild()); } else { // Do nothing. } } else { if (repeatCount > 1) { repeatCountElement.setTextContent(Integer.toString(repeatCount)); } else { repeatCountElement.removeFromParent(); } } } private Element formatRemoteObjectInConsole(RemoteObject remoteObject, DebuggerState debuggerState, boolean forceObjectFormat) { if (forceObjectFormat && remoteObject.hasChildren()) { return formatRemoteObjectInConsoleAsObject(remoteObject, debuggerState); } RemoteObjectType type = remoteObject.getType(); RemoteObjectSubType subType = remoteObject.getSubType(); if (type == RemoteObjectType.OBJECT && (subType == null || subType == RemoteObjectSubType.ARRAY || subType == RemoteObjectSubType.NODE)) { // TODO: Display small ARRAYs inlined. // TODO: Display NODE objects as XML tree some day. return formatRemoteObjectInConsoleAsObject(remoteObject, debuggerState); } Element messageElement = Elements.createSpanElement(css.consolePrimitiveValue()); if (!RemoteObjectType.STRING.equals(type)) { String className = nodeRenderer.getTokenClassName(remoteObject); if (!StringUtils.isNullOrEmpty(className)) { messageElement.addClassName(className); } } messageElement.setTextContent(remoteObject.getDescription()); return messageElement; } private Element formatRemoteObjectInConsoleAsObject(RemoteObject remoteObject, DebuggerState debuggerState) { RemoteObjectTree remoteObjectTree = RemoteObjectTree.create(new RemoteObjectTree.View(resources), resources, debuggerState); remoteObjectTrees.add(remoteObjectTree); RemoteObjectNode newRoot = RemoteObjectNode.createRoot(); RemoteObjectNode child = new RemoteObjectNode.Builder("", remoteObject) .setDeletable(false) .setWritable(false) .build(); newRoot.addChild(child); remoteObjectTree.setRoot(newRoot); Element messageElement = Elements.createSpanElement(css.consoleObject()); messageElement.appendChild(remoteObjectTree.getView().getElement()); return messageElement; } private Element formatLocationLink(String url, int lineNumber, int columnNumber) { // TODO: Do real URL parsing to get the path's last component. String locationName = url; int pos = locationName.lastIndexOf('/'); if (pos != -1) { locationName = locationName.substring(pos + 1); if (StringUtils.isNullOrEmpty(locationName)) { locationName = "/"; } } AnchorElement anchor = Elements.createAnchorElement(css.messageLink()); anchor.setHref(url); anchor.setTarget("_blank"); anchor.setTitle(url); anchor.setTextContent(locationName + ":" + lineNumber); return anchor; } private Element formatStackTrace(JsonArray<StackTraceItem> stackTrace) { Element stackTraceElement = Elements.createDivElement(css.consoleStackTrace()); for (int i = 0, n = stackTrace.size(); i < n; ++i) { StackTraceItem item = stackTrace.get(i); Element itemElement = Elements.createDivElement(css.consoleStackTraceItem()); itemElement.appendChild( formatLocationLink(item.getUrl(), item.getLineNumber(), item.getColumnNumber())); itemElement.appendChild(Elements.createTextNode( StringUtils.ensureNotEmpty(item.getFunctionName(), "(anonymous function)"))); stackTraceElement.appendChild(itemElement); } return stackTraceElement; } private void clearConsoleMessages() { for (int i = 0, n = remoteObjectTrees.size(); i < n; ++i) { remoteObjectTrees.get(i).teardown(); } remoteObjectTrees.clear(); consoleMessages.setInnerHTML(""); } } /** * The view events. */ private interface ViewEvents { // TODO: Add the button into the UI. void onClearConsoleButtonClick(); void onLocationLinkClick(String url, int lineNumber); } static ConsoleView create(View view, DebuggerState debuggerState) { return new ConsoleView(view, debuggerState); } private final DebuggerState debuggerState; private Listener listener; private final DebuggerState.ConsoleListener consoleListener = new DebuggerState.ConsoleListener() { @Override public void onConsoleMessage(ConsoleMessage message) { getView().appendConsoleMessage(message, debuggerState); } @Override public void onConsoleMessageRepeatCountUpdated(ConsoleMessage message, int repeatCount) { getView().updateLastConsoleMessageCount(repeatCount); } @Override public void onConsoleMessagesCleared() { getView().clearConsoleMessages(); } }; private ConsoleView(View view, DebuggerState debuggerState) { super(view); this.debuggerState = debuggerState; debuggerState.getConsoleListenerRegistrar().add(consoleListener); view.setDelegate(new ViewEvents() { @Override public void onClearConsoleButtonClick() { if (ConsoleView.this.debuggerState.isActive()) { // TODO: Implement it in the debugger API. } else { getView().clearConsoleMessages(); } } @Override public void onLocationLinkClick(String url, int lineNumber) { if (listener != null) { listener.onLocationLinkClick(url, lineNumber); } } }); } void setListener(Listener listener) { this.listener = listener; } void show() { // Do nothing. } void hide() { getView().clearConsoleMessages(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/SourceMapping.java
client/src/main/java/com/google/collide/client/code/debugging/SourceMapping.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import javax.annotation.Nullable; import com.google.collide.client.code.debugging.DebuggerApiTypes.BreakpointInfo; import com.google.collide.client.code.debugging.DebuggerApiTypes.Location; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnScriptParsedResponse; import com.google.collide.client.util.PathUtil; /** * Mapping between the local files in the project and remote scripts and * resource files on the debuggee application. */ public interface SourceMapping { /** * @return local {@link PathUtil} path of a given JavaScript source */ public PathUtil getLocalScriptPath(@Nullable OnScriptParsedResponse response); /** * @return line number in the local source corresponding to a given * {@link Location} */ public int getLocalSourceLineNumber(@Nullable OnScriptParsedResponse response, Location location); /** * Converts a local {@link Breakpoint} model to it's remote representation. * * @param breakpoint breakpoint model * @return actual breakpoint to be set in the debuggee application */ public BreakpointInfo getRemoteBreakpoint(Breakpoint breakpoint); /** * @return local {@link PathUtil} path of a given resource */ public PathUtil getLocalSourcePath(String resourceUri); /** * @return remote resource URI corresponding to a given local path */ public String getRemoteSourceUri(PathUtil path); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarHeader.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarHeader.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.util.Elements; import com.google.collide.client.testing.DebugAttributeSetter; import com.google.collide.client.testing.DebugId; import com.google.collide.client.ui.menu.PositionController; import com.google.collide.client.ui.slider.Slider; import com.google.collide.client.ui.tooltip.Tooltip; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; /** * Debugging sidebar header. * * TODO: i18n for the UI strings? * */ public class DebuggingSidebarHeader extends UiComponent<DebuggingSidebarHeader.View> { public interface Css extends CssResource { String root(); String headerLabel(); String slider(); } interface Resources extends ClientBundle, Slider.Resources, Tooltip.Resources { @Source("DebuggingSidebarHeader.css") Css workspaceEditorDebuggingSidebarHeaderCss(); } /** * Listener for the user clicks on the sidebar header. */ interface Listener { void onActivateBreakpoints(); void onDeactivateBreakpoints(); } /** * The view for the sidebar header. */ static class View extends CompositeView<Void> { private final Resources resources; private final Css css; private final Slider.View sliderView; private Tooltip tooltip; View(Resources resources) { this.resources = resources; css = resources.workspaceEditorDebuggingSidebarHeaderCss(); sliderView = new Slider.View(resources); new DebugAttributeSetter().setId(DebugId.DEBUG_BREAKPOINT_SLIDER).on(sliderView.getElement()); Element rootElement = createRootElement(sliderView.getElement()); setElement(rootElement); } Slider.View getSliderView() { return sliderView; } private Element createRootElement(Element sliderContent) { Element element = Elements.createDivElement(css.root()); DomUtils.appendDivWithTextContent(element, css.headerLabel(), "Breakpoints"); Element slider = Elements.createDivElement(css.slider()); slider.appendChild(sliderContent); element.appendChild(slider); return element; } private void setTooltip(boolean active) { if (tooltip != null) { tooltip.destroy(); } String tooltipText = active ? "Deactivate all breakpoints" : "Activate all breakpoints"; tooltip = Tooltip.create(resources, sliderView.getElement(), PositionController.VerticalAlign.BOTTOM, PositionController.HorizontalAlign.MIDDLE, tooltipText); } } static DebuggingSidebarHeader create(View view) { Slider slider = Slider.create(view.getSliderView()); slider.setSliderStrings("ACTIVATED", "DEACTIVATED"); return new DebuggingSidebarHeader(view, slider); } private final Slider slider; private Listener delegateListener; @VisibleForTesting DebuggingSidebarHeader(View view, Slider slider) { super(view); this.slider = slider; getView().setTooltip(true); slider.setListener(new Slider.Listener() { @Override public void onStateChanged(boolean active) { if (delegateListener != null) { if (active) { delegateListener.onActivateBreakpoints(); } else { delegateListener.onDeactivateBreakpoints(); } } getView().setTooltip(active); } }); } void setListener(Listener listener) { delegateListener = listener; } void setAllBreakpointsActive(boolean active) { slider.setActive(active); getView().setTooltip(active); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectTreeContextMenuController.java
client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectTreeContextMenuController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.treeview.TreeNodeElement; import collide.client.treeview.TreeNodeLabelRenamer; import collide.client.treeview.TreeNodeMutator; 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.HorizontalAlign; import com.google.collide.client.ui.menu.PositionController.Positioner; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; import elemental.dom.Element; /** * Handles {@link RemoteObjectTree} tree context menu actions. * */ class RemoteObjectTreeContextMenuController { /** * Callbacks on the context menu actions. */ interface Listener { void onAddNewChild(TreeNodeElement<RemoteObjectNode> node); void onNodeEdited(TreeNodeElement<RemoteObjectNode> node, String newLabel); void onNodeDeleted(TreeNodeElement<RemoteObjectNode> node); void onNodeRenamed(TreeNodeElement<RemoteObjectNode> node, String oldLabel); } /** * A menu item in the context menu. */ private interface TreeNodeMenuItem { public void onClicked(TreeNodeElement<RemoteObjectNode> node); @Override public String toString(); } /** * Renderer for an item in the context menu. */ class TreeItemRenderer extends ListItemRenderer<TreeNodeMenuItem> { @Override public void render(Element listItemBase, TreeNodeMenuItem item) { listItemBase.setTextContent(item.toString()); } } static RemoteObjectTreeContextMenuController create(DropdownWidgets.Resources resources, DebuggerState debuggerState, RemoteObjectNodeRenderer nodeRenderer, TreeNodeLabelRenamer<RemoteObjectNode> nodeLabelMutator) { RemoteObjectTreeContextMenuController controller = new RemoteObjectTreeContextMenuController(debuggerState, nodeRenderer, nodeLabelMutator); controller.installContextMenuController(resources); return controller; } private final DebuggerState debuggerState; private DropdownController<TreeNodeMenuItem> contextDropdownController; private final RemoteObjectNodeRenderer nodeRenderer; private final TreeNodeLabelRenamer<RemoteObjectNode> nodeLabelMutator; private Listener listener; private TreeNodeElement<RemoteObjectNode> selectedNode; private TreeItemRenderer renderer; private TreeNodeMenuItem menuRename; private TreeNodeMenuItem menuDelete; private TreeNodeMenuItem menuAdd; private TreeNodeMenuItem menuEdit; private RemoteObjectTreeContextMenuController(DebuggerState debuggerState, RemoteObjectNodeRenderer nodeRenderer, TreeNodeLabelRenamer<RemoteObjectNode> nodeLabelMutator) { this.debuggerState = debuggerState; this.nodeRenderer = nodeRenderer; this.nodeLabelMutator = nodeLabelMutator; this.renderer = new TreeItemRenderer(); createMenuItems(); } void setListener(Listener listener) { this.listener = listener; } private void installContextMenuController(DropdownWidgets.Resources res) { DropdownController.Listener<TreeNodeMenuItem> listener = new DropdownController.BaseListener<TreeNodeMenuItem>() { @Override public void onItemClicked(TreeNodeMenuItem item) { item.onClicked(selectedNode); } }; Positioner mousePositioner = new DropdownPositionerBuilder().setHorizontalAlign( HorizontalAlign.RIGHT).buildMousePositioner(); contextDropdownController = new DropdownController.Builder<TreeNodeMenuItem>( mousePositioner, null, res, listener, renderer).setShouldAutoFocusOnOpen(true).build(); } void show(int mouseX, int mouseY, TreeNodeElement<RemoteObjectNode> nodeElement) { selectedNode = nodeElement; if (nodeElement == null) { return; } RemoteObjectNode node = nodeElement.getData(); JsonArray<TreeNodeMenuItem> menuItems = JsonCollections.createArray(); if (canAdd(node)) { menuItems.add(menuAdd); } if (canEdit(node)) { menuItems.add(menuEdit); } if (canRenameAndDelete(node)) { menuItems.add(menuRename); menuItems.add(menuDelete); } if (!menuItems.isEmpty()) { contextDropdownController.setItems(menuItems); contextDropdownController.showAtPosition(mouseX, mouseY); } else { contextDropdownController.hide(); } } void hide() { contextDropdownController.hide(); } Element getContextMenuElement() { return contextDropdownController.getElement(); } private boolean canAdd(RemoteObjectNode node) { return node.canAddRemoteObjectProperty(); } private boolean canEdit(RemoteObjectNode node) { return node.isWritable() && debuggerState.isActive() && (node.isRootChild() || isRealRemoteObject(node.getParent())); } private boolean canRenameAndDelete(RemoteObjectNode node) { return node.isDeletable() && (node.isRootChild() || isRealRemoteObject(node.getParent())); } private static boolean isRealRemoteObject(RemoteObjectNode node) { return node != null && node.getRemoteObject() != null && !node.isTransient(); } private void enterAddProperty(TreeNodeElement<RemoteObjectNode> node) { if (listener != null) { listener.onAddNewChild(node); } } boolean enterEditPropertyValue(TreeNodeElement<RemoteObjectNode> nodeToEdit) { if (!canEdit(nodeToEdit.getData())) { return false; } nodeLabelMutator.cancel(); nodeLabelMutator.getTreeNodeMutator().enterMutation( nodeToEdit, new TreeNodeMutator.MutationAction<RemoteObjectNode>() { @Override public Element getElementForMutation(TreeNodeElement<RemoteObjectNode> node) { return nodeRenderer.getPropertyValueElement(node.getNodeLabel()); } @Override public void onBeforeMutation(TreeNodeElement<RemoteObjectNode> node) { nodeRenderer.enterPropertyValueMutation(node.getNodeLabel()); } @Override public void onMutationCommit( TreeNodeElement<RemoteObjectNode> node, String oldLabel, String newLabel) { String trimmedLabel = StringUtils.trimNullToEmpty(newLabel); nodeRenderer.exitPropertyValueMutation(node.getNodeLabel(), trimmedLabel); if (listener != null && !StringUtils.equalStringsOrEmpty(oldLabel, trimmedLabel)) { listener.onNodeEdited(node, trimmedLabel); } } @Override public boolean passValidation(TreeNodeElement<RemoteObjectNode> node, String newLabel) { return !StringUtils.isNullOrWhitespace(newLabel); } }); return true; } boolean enterRenameProperty(TreeNodeElement<RemoteObjectNode> nodeToRename) { if (!canRenameAndDelete(nodeToRename.getData())) { return false; } nodeLabelMutator.cancel(); nodeLabelMutator.enterMutation( nodeToRename, new TreeNodeLabelRenamer.LabelRenamerCallback<RemoteObjectNode>() { @Override public void onCommit(String oldLabel, TreeNodeElement<RemoteObjectNode> node) { if (listener != null && !oldLabel.equals(node.getData().getName())) { listener.onNodeRenamed(node, oldLabel); } } @Override public boolean passValidation(TreeNodeElement<RemoteObjectNode> node, String newLabel) { return !StringUtils.isNullOrWhitespace(newLabel); } }); return true; } private void enterDeleteProperty(TreeNodeElement<RemoteObjectNode> node) { if (listener != null) { listener.onNodeDeleted(node); } } private void createMenuItems() { menuRename = new TreeNodeMenuItem() { @Override public void onClicked(TreeNodeElement<RemoteObjectNode> node) { enterRenameProperty(node); } @Override public String toString() { return "Rename"; } }; menuDelete = new TreeNodeMenuItem() { @Override public void onClicked(TreeNodeElement<RemoteObjectNode> node) { enterDeleteProperty(node); } @Override public String toString() { return "Delete"; } }; menuAdd = new TreeNodeMenuItem() { @Override public void onClicked(TreeNodeElement<RemoteObjectNode> node) { enterAddProperty(node); } @Override public String toString() { return "Add"; } }; menuEdit = new TreeNodeMenuItem() { @Override public void onClicked(TreeNodeElement<RemoteObjectNode> node) { enterEditPropertyValue(node); } @Override public String toString() { return "Edit"; } }; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggerChromeApi.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggerChromeApi.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import com.google.collide.client.code.debugging.DebuggerApiTypes.BreakpointInfo; import com.google.collide.client.code.debugging.DebuggerApiTypes.CallFrame; import com.google.collide.client.code.debugging.DebuggerApiTypes.ConsoleMessage; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnAllCssStyleSheetsResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnBreakpointResolvedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnEvaluateExpressionResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnPausedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnRemoteObjectPropertiesResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnRemoteObjectPropertyChanged; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnScriptParsedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.PauseOnExceptionsState; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectId; import com.google.collide.client.util.JsIntegerMap; import com.google.collide.client.util.logging.Log; import com.google.collide.json.client.Jso; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; import elemental.client.Browser; import elemental.events.CustomEvent; import elemental.events.Event; import elemental.events.EventListener; import elemental.events.EventRemover; /** * Implements communication API with the Chrome browser debugger. * * <p>On the side of the Chrome browser the "Collide Debugger" extension should * be installed to accept the requests from the Collide client. */ class DebuggerChromeApi implements DebuggerApi { // TODO: Replace the URL when extension is public. private static final String EXTENSION_URL = "http://www.example.com/collide.crx"; private static final String DEBUGGER_EXTENSION_REQUEST_EVENT = "DebuggerExtensionRequest"; private static final String DEBUGGER_EXTENSION_RESPONSE_EVENT = "DebuggerExtensionResponse"; private static final String METHOD_WINDOW_OPEN = "window.open"; private static final String METHOD_WINDOW_CLOSE = "window.close"; private static final String METHOD_ON_ATTACH = "onAttach"; private static final String METHOD_ON_DETACH = "onDetach"; private static final String METHOD_ON_GLOBAL_OBJECT_CHANGED = "onGlobalObjectChanged"; private static final String METHOD_ON_EXTENSION_INSTALLED_CHANGED = "onExtensionInstalledChanged"; private static final String METHOD_CSS_GET_ALL_STYLE_SHEETS = "CSS.getAllStyleSheets"; private static final String METHOD_CSS_SET_STYLE_SHEET_TEXT = "CSS.setStyleSheetText"; private static final String METHOD_CONSOLE_ENABLE = "Console.enable"; private static final String METHOD_CONSOLE_MESSAGE_ADDED = "Console.messageAdded"; private static final String METHOD_CONSOLE_MESSAGE_REPEAT_COUNT_UPDATED = "Console.messageRepeatCountUpdated"; private static final String METHOD_CONSOLE_MESSAGES_CLEARED = "Console.messagesCleared"; private static final String METHOD_DEBUGGER_ENABLE = "Debugger.enable"; private static final String METHOD_DEBUGGER_SET_BREAKPOINT_BY_URL = "Debugger.setBreakpointByUrl"; private static final String METHOD_DEBUGGER_REMOVE_BREAKPOINT = "Debugger.removeBreakpoint"; private static final String METHOD_DEBUGGER_SET_BREAKPOINTS_ACTIVE = "Debugger.setBreakpointsActive"; private static final String METHOD_DEBUGGER_SET_PAUSE_ON_EXCEPTIONS = "Debugger.setPauseOnExceptions"; private static final String METHOD_DEBUGGER_PAUSE = "Debugger.pause"; private static final String METHOD_DEBUGGER_RESUME = "Debugger.resume"; private static final String METHOD_DEBUGGER_STEP_INTO = "Debugger.stepInto"; private static final String METHOD_DEBUGGER_STEP_OUT = "Debugger.stepOut"; private static final String METHOD_DEBUGGER_STEP_OVER = "Debugger.stepOver"; private static final String METHOD_DEBUGGER_EVALUATE_ON_CALL_FRAME = "Debugger.evaluateOnCallFrame"; private static final String METHOD_RUNTIME_CALL_FUNCTION_ON = "Runtime.callFunctionOn"; private static final String METHOD_RUNTIME_EVALUATE = "Runtime.evaluate"; private static final String METHOD_RUNTIME_GET_PROPERTIES = "Runtime.getProperties"; private static final String EVENT_DEBUGGER_BREAKPOINT_RESOLVED = "Debugger.breakpointResolved"; private static final String EVENT_DEBUGGER_SCRIPT_PARSED = "Debugger.scriptParsed"; private static final String EVENT_DEBUGGER_PAUSED = "Debugger.paused"; private static final String EVENT_DEBUGGER_RESUMED = "Debugger.resumed"; private final JsonArray<DebuggerResponseListener> debuggerResponseListeners = JsonCollections.createArray(); private final EventRemover debuggerExtensionListenerRemover; private int lastUsedId = 0; private JsonStringMap<JsIntegerMap<Integer>> idToCustomMessageIds = JsonCollections.createMap(); private JsonStringMap<JsIntegerMap<Callback>> callbacks = JsonCollections.createMap(); private final EventListener debuggerExtensionResponseListener = new EventListener() { @Override public void handleEvent(Event evt) { Object detail = ((CustomEvent) evt).getDetail(); if (detail != null) { handleDebuggerExtensionResponse(new ExtensionResponse(Jso.deserialize(detail.toString()))); } } }; private static class ExtensionResponse { private final Jso response; ExtensionResponse(Jso response) { this.response = response; } int messageId() { return response.getFieldCastedToInteger("id"); } String sessionId() { return response.getStringField("target"); } String methodName() { return response.getStringField("method"); } Jso request() { return response.getJsObjectField("request").cast(); } Jso result() { return response.getJsObjectField("result").cast(); } String errorMessage() { return response.getStringField("error"); } boolean isError() { return !StringUtils.isNullOrEmpty(errorMessage()); } } private interface DebuggerResponseDispatcher { void dispatch(DebuggerResponseListener responseListener); } private interface Callback { void run(ExtensionResponse response); } public DebuggerChromeApi() { debuggerExtensionListenerRemover = Browser.getWindow().addEventListener( DEBUGGER_EXTENSION_RESPONSE_EVENT, debuggerExtensionResponseListener, false); } public void teardown() { debuggerResponseListeners.clear(); debuggerExtensionListenerRemover.remove(); idToCustomMessageIds = JsonCollections.createMap(); callbacks = JsonCollections.createMap(); } @Override public final native boolean isDebuggerAvailable() /*-{ try { return !!top["__DebuggerExtensionInstalled"]; } catch (e) { } return false; }-*/; @Override public String getDebuggingExtensionUrl() { return EXTENSION_URL; } @Override public void runDebugger(String sessionId, String url) { Jso params = Jso.create(); params.addField("url", url); sendCustomEvent(sessionId, METHOD_WINDOW_OPEN, params); sendCustomEvent(sessionId, METHOD_DEBUGGER_ENABLE, null); sendCustomEvent(sessionId, METHOD_CONSOLE_ENABLE, null); } @Override public void shutdownDebugger(String sessionId) { sendCustomEvent(sessionId, METHOD_WINDOW_CLOSE, null); } @Override public void setBreakpointByUrl(String sessionId, BreakpointInfo breakpointInfo) { String condition = breakpointInfo.getCondition(); Jso params = Jso.create(); if (breakpointInfo.getUrl() != null) { params.addField("url", breakpointInfo.getUrl()); } else { params.addField("urlRegex", breakpointInfo.getUrlRegex()); } params.addField("lineNumber", breakpointInfo.getLineNumber()); params.addField("columnNumber", breakpointInfo.getColumnNumber()); params.addField("condition", condition == null ? "" : condition); sendCustomEvent(sessionId, METHOD_DEBUGGER_SET_BREAKPOINT_BY_URL, params); } @Override public void removeBreakpoint(String sessionId, String breakpointId) { Jso params = Jso.create(); params.addField("breakpointId", breakpointId); sendCustomEvent(sessionId, METHOD_DEBUGGER_REMOVE_BREAKPOINT, params); } @Override public void setBreakpointsActive(String sessionId, boolean active) { Jso params = Jso.create(); params.addField("active", active); sendCustomEvent(sessionId, METHOD_DEBUGGER_SET_BREAKPOINTS_ACTIVE, params); } @Override public void setPauseOnExceptions(String sessionId, PauseOnExceptionsState state) { Jso params = Jso.create(); params.addField("state", state.toString().toLowerCase()); sendCustomEvent(sessionId, METHOD_DEBUGGER_SET_PAUSE_ON_EXCEPTIONS, params); } @Override public void pause(String sessionId) { sendCustomEvent(sessionId, METHOD_DEBUGGER_PAUSE, null); } @Override public void resume(String sessionId) { sendCustomEvent(sessionId, METHOD_DEBUGGER_RESUME, null); } @Override public void stepInto(String sessionId) { sendCustomEvent(sessionId, METHOD_DEBUGGER_STEP_INTO, null); } @Override public void stepOut(String sessionId) { sendCustomEvent(sessionId, METHOD_DEBUGGER_STEP_OUT, null); } @Override public void stepOver(String sessionId) { sendCustomEvent(sessionId, METHOD_DEBUGGER_STEP_OVER, null); } @Override public void requestRemoteObjectProperties(String sessionId, RemoteObjectId remoteObjectId) { Jso params = Jso.create(); params.addField("objectId", remoteObjectId.toString()); params.addField("ownProperties", true); sendCustomEvent(sessionId, METHOD_RUNTIME_GET_PROPERTIES, params); } @Override public void setRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { String expression = preparePropertyValueExpression(propertyValueExpression); evaluateExpression(sessionId, expression, createSetRemoteObjectPropertyCallback(sessionId, remoteObjectId, propertyName)); } @Override public void setRemoteObjectPropertyEvaluatedOnCallFrame(String sessionId, CallFrame callFrame, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { String expression = preparePropertyValueExpression(propertyValueExpression); evaluateExpressionOnCallFrame(sessionId, callFrame, expression, createSetRemoteObjectPropertyCallback(sessionId, remoteObjectId, propertyName)); } /** * This will wrap the given expression into braces if it looks like a * JavaScript object syntax. * * <p>We do this just for the user's convenience overriding the semantics of * the {@code window.eval} method, that evaluates the <i>"{}"</i> into * {@code undefined}, and <i>"{foo:123}"</i> into {@code 123}. */ private String preparePropertyValueExpression(String expression) { if (StringUtils.firstNonWhitespaceCharacter(expression) == '{' && StringUtils.lastNonWhitespaceCharacter(expression) == '}') { return "(" + expression + ")"; } return expression; } private Callback createSetRemoteObjectPropertyCallback(final String sessionId, final RemoteObjectId remoteObjectId, final String propertyName) { return new Callback() { @Override public void run(ExtensionResponse evaluationResponse) { OnEvaluateExpressionResponse evaluationParsedResponse = DebuggerChromeApiUtils.parseOnEvaluateExpressionResponse( evaluationResponse.request(), evaluationResponse.result()); boolean isError = evaluationResponse.isError() || evaluationParsedResponse == null || evaluationParsedResponse.wasThrown() || evaluationParsedResponse.getResult() == null; final RemoteObject evaluationResult = isError ? null : evaluationParsedResponse.getResult(); Jso params = Jso.create(); if (!isError && DebuggerApiUtils.isNonFiniteNumber(evaluationResult)) { params.addField("functionDeclaration", "function(a) {" + " this[a] = " + evaluationResult.getDescription() + ";" + " return this[a];" + "}"); params.addField("objectId", remoteObjectId.toString()); JsonArray<Jso> arguments = JsonCollections.createArray(); arguments.add(Jso.create()); arguments.get(0).addField("value", propertyName); params.addField("arguments", arguments); } else if (!isError) { params.addField("functionDeclaration", "function(a, b) { this[a] = b; return this[a]; }"); params.addField("objectId", remoteObjectId.toString()); JsonArray<Jso> arguments = JsonCollections.createArray(); arguments.add(Jso.create()); arguments.add(Jso.create()); arguments.get(0).addField("value", propertyName); if (evaluationResult.getObjectId() == null) { if (!DebuggerApiUtils.addPrimitiveJsoField( arguments.get(1), "value", evaluationResult)) { isError = true; } } else { arguments.get(1).addField("objectId", evaluationResult.getObjectId().toString()); } params.addField("arguments", arguments); } if (isError) { // We do not know the property value. Just dispatch the error event. OnRemoteObjectPropertyChanged parsedResponse = DebuggerChromeApiUtils.createOnEditRemoteObjectPropertyResponse( remoteObjectId, propertyName, null, true); dispatchOnRemoteObjectPropertyChanged(sessionId, parsedResponse); return; } sendCustomEvent(sessionId, METHOD_RUNTIME_CALL_FUNCTION_ON, params, new Callback() { @Override public void run(ExtensionResponse response) { RemoteObject newValue = DebuggerChromeApiUtils.parseCallFunctionOnResult(response.result()); boolean isError = response.isError() || newValue == null || !DebuggerApiUtils.equal(evaluationResult, newValue); OnRemoteObjectPropertyChanged parsedResponse = DebuggerChromeApiUtils.createOnEditRemoteObjectPropertyResponse( remoteObjectId, propertyName, newValue, isError); dispatchOnRemoteObjectPropertyChanged(sessionId, parsedResponse); } }); } }; } @Override public void removeRemoteObjectProperty(final String sessionId, final RemoteObjectId remoteObjectId, final String propertyName) { Jso params = Jso.create(); params.addField("functionDeclaration", "function(a) { delete this[a]; return !(a in this); }"); params.addField("objectId", remoteObjectId.toString()); JsonArray<Jso> arguments = JsonCollections.createArray(); arguments.add(Jso.create()); arguments.get(0).addField("value", propertyName); params.addField("arguments", arguments); sendCustomEvent(sessionId, METHOD_RUNTIME_CALL_FUNCTION_ON, params, new Callback() { @Override public void run(ExtensionResponse response) { boolean isError = response.isError() || !DebuggerApiUtils.castToBoolean( DebuggerChromeApiUtils.parseCallFunctionOnResult(response.result())); OnRemoteObjectPropertyChanged parsedResponse = DebuggerChromeApiUtils.createOnRemoveRemoteObjectPropertyResponse( remoteObjectId, propertyName, isError); dispatchOnRemoteObjectPropertyChanged(sessionId, parsedResponse); } }); } @Override public void renameRemoteObjectProperty(final String sessionId, final RemoteObjectId remoteObjectId, final String oldName, final String newName) { Jso params = Jso.create(); params.addField("functionDeclaration", "function(a, b) {" + " if (a === b) return true;" + " this[b] = this[a];" + " if (this[b] !== this[a]) return false;" + " delete this[a];" + " return !(a in this);" + "}"); params.addField("objectId", remoteObjectId.toString()); JsonArray<Jso> arguments = JsonCollections.createArray(); arguments.add(Jso.create()); arguments.add(Jso.create()); arguments.get(0).addField("value", oldName); arguments.get(1).addField("value", newName); params.addField("arguments", arguments); sendCustomEvent(sessionId, METHOD_RUNTIME_CALL_FUNCTION_ON, params, new Callback() { @Override public void run(ExtensionResponse response) { boolean isError = response.isError() || !DebuggerApiUtils.castToBoolean( DebuggerChromeApiUtils.parseCallFunctionOnResult(response.result())); OnRemoteObjectPropertyChanged parsedResponse = DebuggerChromeApiUtils.createOnRenameRemoteObjectPropertyResponse( remoteObjectId, oldName, newName, isError); dispatchOnRemoteObjectPropertyChanged(sessionId, parsedResponse); } }); } @Override public void evaluateExpression(String sessionId, String expression) { evaluateExpression(sessionId, expression, null); } private void evaluateExpression(String sessionId, String expression, Callback callback) { Jso params = Jso.create(); params.addField("expression", expression); params.addField("doNotPauseOnExceptions", true); sendCustomEvent(sessionId, METHOD_RUNTIME_EVALUATE, params, callback); } @Override public void evaluateExpressionOnCallFrame(String sessionId, CallFrame callFrame, String expression) { evaluateExpressionOnCallFrame(sessionId, callFrame, expression, null); } private void evaluateExpressionOnCallFrame(String sessionId, CallFrame callFrame, String expression, Callback callback) { Jso params = Jso.create(); params.addField("expression", expression); params.addField("callFrameId", callFrame.getId()); sendCustomEvent(sessionId, METHOD_DEBUGGER_EVALUATE_ON_CALL_FRAME, params, callback); } @Override public void requestAllCssStyleSheets(String sessionId) { sendCustomEvent(sessionId, METHOD_CSS_GET_ALL_STYLE_SHEETS, null); } @Override public void setStyleSheetText(String sessionId, String styleSheetId, String text) { Jso params = Jso.create(); params.addField("styleSheetId", styleSheetId); params.addField("text", text); sendCustomEvent(sessionId, METHOD_CSS_SET_STYLE_SHEET_TEXT, params); } @Override public void sendCustomMessage(String sessionId, String message) { Jso messageObject = Jso.deserialize(message); if (messageObject == null) { return; } JsIntegerMap<Integer> map = idToCustomMessageIds.get(sessionId); if (map == null) { map = JsIntegerMap.create(); idToCustomMessageIds.put(sessionId, map); } map.put(lastUsedId + 1, messageObject.getIntField("id")); sendCustomEvent(sessionId, messageObject.getStringField("method"), (Jso) messageObject.getObjectField("params")); } @Override public void addDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener) { debuggerResponseListeners.add(debuggerResponseListener); } @Override public void removeDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener) { debuggerResponseListeners.remove(debuggerResponseListener); } private void sendCustomEvent(String sessionId, String methodName, Jso params) { sendCustomEvent(sessionId, methodName, params, null); } private void sendCustomEvent(String sessionId, String methodName, Jso params, Callback callback) { Log.debug(getClass(), "Sending message to the debugger: " + methodName); final int id = ++lastUsedId; Jso data = Jso.create(); data.addField("id", id); data.addField("target", sessionId); data.addField("method", methodName); if (params != null) { data.addField("params", params); } if (callback != null) { JsIntegerMap<Callback> map = callbacks.get(sessionId); if (map == null) { map = JsIntegerMap.create(); callbacks.put(sessionId, map); } map.put(id, callback); } CustomEvent evt = (CustomEvent) Browser.getDocument().createEvent("CustomEvent"); evt.initCustomEvent(DEBUGGER_EXTENSION_REQUEST_EVENT, true, true, Jso.serialize(data)); Browser.getWindow().dispatchEvent(evt); } private void handleDebuggerExtensionResponse(ExtensionResponse response) { if (maybeInvokeCallbackForResponse(response)) { return; } if (maybeHandleDebuggerCustomMessageResponse(response)) { return; } final String sessionId = response.sessionId(); final String methodName = response.methodName(); final Jso request = response.request(); final Jso result = response.result(); Log.debug(getClass(), "Received debugger message: " + methodName); if (response.isError()) { Log.debug(getClass(), "Received debugger error message: " + response.errorMessage()); handleDebuggerExtensionErrorResponse(sessionId, methodName); return; } if (EVENT_DEBUGGER_SCRIPT_PARSED.equals(methodName)) { // The most frequent event. final OnScriptParsedResponse parsedResponse = DebuggerChromeApiUtils.parseOnScriptParsedResponse(result); if (parsedResponse != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onScriptParsed(sessionId, parsedResponse); } }); } } else if (METHOD_CONSOLE_MESSAGE_ADDED.equals(methodName)) { final ConsoleMessage consoleMessage = DebuggerChromeApiUtils.parseOnConsoleMessageReceived(result); if (consoleMessage != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onConsoleMessage(sessionId, consoleMessage); } }); } } else if (METHOD_CONSOLE_MESSAGE_REPEAT_COUNT_UPDATED.equals(methodName)) { final int repeatCount = DebuggerChromeApiUtils.parseOnConsoleMessageRepeatCountUpdated(result); if (repeatCount != -1) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onConsoleMessageRepeatCountUpdated(sessionId, repeatCount); } }); } } else if (EVENT_DEBUGGER_PAUSED.equals(methodName)) { final OnPausedResponse parsedResponse = DebuggerChromeApiUtils.parseOnPausedResponse(result); if (parsedResponse != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onPaused(sessionId, parsedResponse); } }); } } else if (EVENT_DEBUGGER_RESUMED.equals(methodName)) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onResumed(sessionId); } }); } else if (METHOD_DEBUGGER_SET_BREAKPOINT_BY_URL.equals(methodName) || EVENT_DEBUGGER_BREAKPOINT_RESOLVED.equals(methodName)) { final OnBreakpointResolvedResponse parsedResponse = DebuggerChromeApiUtils.parseOnBreakpointResolvedResponse(request, result); if (parsedResponse != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onBreakpointResolved(sessionId, parsedResponse); } }); } } else if (METHOD_DEBUGGER_REMOVE_BREAKPOINT.equals(methodName)) { final String breakpointId = DebuggerChromeApiUtils.parseOnRemoveBreakpointResponse(request); if (breakpointId != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onBreakpointRemoved(sessionId, breakpointId); } }); } } else if (METHOD_ON_ATTACH.equals(methodName) || METHOD_WINDOW_OPEN.equals(methodName)) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onDebuggerAttached(sessionId); } }); } else if (METHOD_ON_DETACH.equals(methodName) || METHOD_WINDOW_CLOSE.equals(methodName)) { dispatchOnDebuggerDetachedEvent(sessionId); } else if (METHOD_ON_GLOBAL_OBJECT_CHANGED.equals(methodName)) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onGlobalObjectChanged(sessionId); } }); } else if (METHOD_RUNTIME_GET_PROPERTIES.equals(methodName)) { final OnRemoteObjectPropertiesResponse parsedResponse = DebuggerChromeApiUtils.parseOnRemoteObjectPropertiesResponse(request, result); if (parsedResponse != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onRemoteObjectPropertiesResponse(sessionId, parsedResponse); } }); } } else if (METHOD_RUNTIME_EVALUATE.equals(methodName) || METHOD_DEBUGGER_EVALUATE_ON_CALL_FRAME.equals(methodName)) { final OnEvaluateExpressionResponse parsedResponse = DebuggerChromeApiUtils.parseOnEvaluateExpressionResponse(request, result); if (parsedResponse != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onEvaluateExpressionResponse(sessionId, parsedResponse); } }); } } else if (METHOD_CSS_GET_ALL_STYLE_SHEETS.equals(methodName)) { final OnAllCssStyleSheetsResponse parsedResponse = DebuggerChromeApiUtils.parseOnAllCssStyleSheetsResponse(result); if (parsedResponse != null) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onAllCssStyleSheetsResponse(sessionId, parsedResponse); } }); } } else if (METHOD_ON_EXTENSION_INSTALLED_CHANGED.equals(methodName)) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onDebuggerAvailableChanged(); } }); } else if (METHOD_CONSOLE_MESSAGES_CLEARED.equals(methodName)) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onConsoleMessagesCleared(sessionId); } }); } else { Log.warn(getClass(), "Ignoring debugger message: " + methodName); } } private boolean maybeInvokeCallbackForResponse(ExtensionResponse response) { final int messageId = response.messageId(); final String sessionId = response.sessionId(); if (callbacks.get(sessionId) != null && callbacks.get(sessionId).hasKey(messageId)) { JsIntegerMap<Callback> map = callbacks.get(sessionId); Callback callback = map.get(messageId); map.erase(messageId); callback.run(response); return true; } return false; } private boolean maybeHandleDebuggerCustomMessageResponse(ExtensionResponse response) { final int messageId = response.messageId(); final String sessionId = response.sessionId(); final String methodName = response.methodName(); final Jso result = response.result(); if (idToCustomMessageIds.get(sessionId) != null && idToCustomMessageIds.get(sessionId).hasKey(messageId)) { JsIntegerMap<Integer> map = idToCustomMessageIds.get(sessionId); Jso customResponse = Jso.create(); customResponse.addField("id", map.get(messageId).intValue()); customResponse.addField("result", result); if (response.isError()) { customResponse.addField("error", response.errorMessage()); } final String customResponseSerialized = Jso.serialize(customResponse); map.erase(messageId); dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onCustomMessageResponse(sessionId, customResponseSerialized); } }); return true; } else if (methodName.startsWith("DOM.")) { Jso customResponse = Jso.create(); customResponse.addField("method", methodName); customResponse.addField("params", result); if (response.isError()) { customResponse.addField("error", response.errorMessage()); } final String customResponseSerialized = Jso.serialize(customResponse); dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onCustomMessageResponse(sessionId, customResponseSerialized); } }); return true; } return false; } private void handleDebuggerExtensionErrorResponse(String sessionId, String methodName) { // Dispatch the onDebuggerDetached internal event for each failed method // that might have actually detached the remote debugger. if (METHOD_ON_ATTACH.equals(methodName) || METHOD_WINDOW_OPEN.equals(methodName) || METHOD_ON_DETACH.equals(methodName) || METHOD_WINDOW_CLOSE.equals(methodName)) { dispatchOnDebuggerDetachedEvent(sessionId); } } private void dispatchOnDebuggerDetachedEvent(final String sessionId) { // Clear cached data for the debugger session. idToCustomMessageIds.remove(sessionId); callbacks.remove(sessionId); dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onDebuggerDetached(sessionId); } }); } private void dispatchOnRemoteObjectPropertyChanged(final String sessionId, final OnRemoteObjectPropertyChanged parsedResponse) { dispatchDebuggerResponse(new DebuggerResponseDispatcher() { @Override public void dispatch(DebuggerResponseListener responseListener) { responseListener.onRemoteObjectPropertyChanged(sessionId, parsedResponse); } }); } private void dispatchDebuggerResponse(DebuggerResponseDispatcher dispatcher) { JsonArray<DebuggerResponseListener> copy = debuggerResponseListeners.copy(); for (int i = 0, n = copy.size(); i < n; i++) { dispatcher.dispatch(copy.get(i)); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectNode.java
client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectNode.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.treeview.TreeNodeElement; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectSubType; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.SortedList; import com.google.collide.shared.util.StringUtils; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; /** * Represents a {@link RemoteObject} node in the tree UI. * */ class RemoteObjectNode implements Comparable<RemoteObjectNode> { private static final String GETTER_PROPERTY_PREFIX = "get "; private static final String SETTER_PROPERTY_PREFIX = "set "; private static final String PROTO_PROPERTY_NAME = "__proto__"; private static final RegExp CHUNK_FROM_BEGINNING = RegExp.compile("(^\\d+)|(^\\D+)"); private static final SortedList.Comparator<RemoteObjectNode> SORTING_FUNCTION = new SortedList.Comparator<RemoteObjectNode>() { @Override public int compare(RemoteObjectNode a, RemoteObjectNode b) { return a.compareTo(b); } }; private String name; private final int orderIndex; private final SortedList<RemoteObjectNode> children; private final RemoteObject remoteObject; private final boolean wasThrown; private final boolean isDeletable; private final boolean isWritable; private final boolean isEnumerable; private final String getterOrSetterName; private final boolean isTransient; private boolean shouldRequestChildren; public static RemoteObjectNode createRoot() { return new Builder("/") .setHasChildren(true) .setDeletable(false) .build(); } public static RemoteObjectNode createGetterProperty(String name, RemoteObject getterFunction) { return new Builder(GETTER_PROPERTY_PREFIX + name, getterFunction) .setGetterOrSetterName(name) .build(); } public static RemoteObjectNode createSetterProperty(String name, RemoteObject setterFunction) { return new Builder(SETTER_PROPERTY_PREFIX + name, setterFunction) .setGetterOrSetterName(name) .build(); } public static RemoteObjectNode createBeingEdited() { return new Builder("") .setOrderIndex(Integer.MAX_VALUE) .build(); } private static RemoteObjectNode createNoPropertiesPlaceholder() { // TODO: i18n? return new Builder("No Properties") .setDeletable(false) .setWritable(false) .build(); } private RemoteObjectNode(Builder builder) { this.name = builder.name; this.orderIndex = builder.orderIndex; this.children = (builder.hasChildren && !builder.wasThrown) ? new SortedList<RemoteObjectNode>(SORTING_FUNCTION) : null; this.remoteObject = builder.remoteObject; this.wasThrown = builder.wasThrown; this.getterOrSetterName = builder.getterOrSetterName; this.isTransient = builder.isTransient; boolean isDeletable = builder.isDeletable; boolean isWritable = builder.isWritable; boolean isEnumerable = builder.isEnumerable; if (PROTO_PROPERTY_NAME.equals(name)) { // The __proto__ property can not be deleted, although can be changed. isDeletable = false; isEnumerable = false; } if (getterOrSetterName != null) { // TODO: Maybe allow editing and/or deleting getters and setters? isDeletable = false; isWritable = false; } this.isDeletable = isDeletable; this.isWritable = isWritable; this.isEnumerable = isEnumerable; this.shouldRequestChildren = (!wasThrown && remoteObject != null && remoteObject.hasChildren()); } /** * Tears down the object in order to prevent leaks. Do not use the object once * this method is called. */ public void teardown() { if (children != null) { children.clear(); } setParent(null); setRenderedTreeNode(null); } public String getName() { return name; } public void setName(String name) { RemoteObjectNode parent = getParent(); if (parent != null) { parent.removeChild(this); } this.name = name; if (parent != null) { parent.addChild(this); } } public int getOrderIndex() { return orderIndex; } public String getNodeId() { return name + "#" + orderIndex; } public native final RemoteObjectNode getParent() /*-{ return this.__parentRef; }-*/; private native void setParent(RemoteObjectNode parent) /*-{ this.__parentRef = parent; }-*/; public boolean hasChildren() { return children != null; } public boolean wasThrown() { return wasThrown; } public boolean canAddRemoteObjectProperty() { if (isTransient || remoteObject == null || !hasChildren()) { return false; } RemoteObjectType type = remoteObject.getType(); RemoteObjectSubType subType = remoteObject.getSubType(); return type == RemoteObjectType.FUNCTION || (type == RemoteObjectType.OBJECT && subType != RemoteObjectSubType.NULL); } /** * @return true if this property can be deleted from the parent object */ public boolean isDeletable() { return isDeletable; } /** * @return true if the value of this property can be changed */ public boolean isWritable() { return isWritable; } public boolean isEnumerable() { return isEnumerable; } /** * @return true if the object represented by this node refers to an artificial * transient remote object * @see DebuggerApiTypes.Scope#isTransient */ public boolean isTransient() { return isTransient; } public boolean shouldRequestChildren() { return shouldRequestChildren && hasChildren(); } public void setAllChildrenRequested() { shouldRequestChildren = false; } public JsonArray<RemoteObjectNode> getChildren() { if (children == null) { return JsonCollections.createArray(); } // Some remote objects may have no children. In this case we return a // special "placeholder" child to display this fact in the UI. if (children.size() == 0 && remoteObject != null && !shouldRequestChildren) { addChild(createNoPropertiesPlaceholder()); } return children.toArray(); // Returns copy. } public RemoteObject getRemoteObject() { return remoteObject; } /** * @return the associated rendered {@link TreeNodeElement}. If there is no * tree node element rendered yet, then {@code null} is returned */ public final native TreeNodeElement<RemoteObjectNode> getRenderedTreeNode() /*-{ return this.__renderedNode; }-*/; /** * Associates this RemoteObjectNode 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<RemoteObjectNode> renderedNode) /*-{ this.__renderedNode = renderedNode; }-*/; public boolean isRootChild() { return getParent() != null && getParent().getParent() == null; } @Override public int compareTo(RemoteObjectNode that) { if (this == that) { return 0; } int orderIndexDiff = this.orderIndex - that.orderIndex; if (orderIndexDiff != 0) { return orderIndexDiff; } String a = this.getName(); String b = that.getName(); if (PROTO_PROPERTY_NAME.equals(a)) { return 1; } if (PROTO_PROPERTY_NAME.equals(b)) { return -1; } // Sort by digits/non-digits chunks. while (true) { boolean emptyA = StringUtils.isNullOrEmpty(a); boolean emptyB = StringUtils.isNullOrEmpty(b); if (emptyA && emptyB) { return 0; } if (emptyA && !emptyB) { return -1; } if (emptyB && !emptyA) { return 1; } MatchResult resultA = CHUNK_FROM_BEGINNING.exec(a); MatchResult resultB = CHUNK_FROM_BEGINNING.exec(b); String chunkA = resultA.getGroup(0); String chunkB = resultB.getGroup(0); boolean isNumA = !StringUtils.isNullOrEmpty(resultA.getGroup(1)); boolean isNumB = !StringUtils.isNullOrEmpty(resultB.getGroup(1)); if (isNumA && !isNumB) { return -1; } if (isNumB && !isNumA) { return 1; } if (isNumA && isNumB) { // Must be parseDouble to handle big integers. double valueA = Double.parseDouble(chunkA); double valueB = Double.parseDouble(chunkB); if (valueA != valueB) { return valueA < valueB ? -1 : 1; } int diff = chunkA.length() - chunkB.length(); if (diff != 0) { if (valueA == 0) { // "file_0" should precede "file_00". return diff; } else { // "file_015" should precede "file_15". return -diff; } } } else { int diff = chunkA.compareTo(chunkB); if (diff != 0) { return diff; } } a = a.substring(chunkA.length()); b = b.substring(chunkB.length()); } } public void addChild(RemoteObjectNode remoteObjectNode) { assert (hasChildren()) : "Adding children to a leaf node is not allowed!"; remoteObjectNode.setParent(this); children.add(remoteObjectNode); } public void removeChild(RemoteObjectNode remoteObjectNode) { assert (hasChildren()) : "Removing a child from a leaf node?!"; children.remove(remoteObjectNode); } public RemoteObjectNode getFirstChildByName(String name) { if (children == null) { return null; } for (int i = 0, n = children.size(); i < n; ++i) { RemoteObjectNode child = children.get(i); if (name.equals(child.getName())) { return child; } } return null; } public RemoteObjectNode getLastChild() { if (children == null || children.size() == 0) { return null; } return children.get(children.size() - 1); } /** * Builder class for the {@link RemoteObjectNode}. */ public static class Builder { private final String name; private final RemoteObject remoteObject; private int orderIndex; private boolean hasChildren; private boolean wasThrown; private boolean isDeletable = true; private boolean isWritable = true; private boolean isEnumerable = true; private boolean isTransient; private String getterOrSetterName; public Builder(String name) { this(name, null); } public Builder(String name, RemoteObject remoteObject) { this(name, remoteObject, null); } public Builder(String name, RemoteObject remoteObject, RemoteObjectNode proto) { this.name = name; this.remoteObject = remoteObject; this.hasChildren = (remoteObject != null && remoteObject.hasChildren()); if (proto != null) { this.orderIndex = proto.orderIndex; this.wasThrown = proto.wasThrown; this.isDeletable = proto.isDeletable; this.isWritable = proto.isWritable; this.isEnumerable = proto.isEnumerable; this.isTransient = proto.isTransient; this.getterOrSetterName = proto.getterOrSetterName; } } public Builder setOrderIndex(int orderIndex) { this.orderIndex = orderIndex; return this; } public Builder setHasChildren(boolean hasChildren) { this.hasChildren = hasChildren; return this; } public Builder setWasThrown(boolean wasThrown) { this.wasThrown = wasThrown; return this; } public Builder setDeletable(boolean deletable) { isDeletable = deletable; return this; } public Builder setWritable(boolean writable) { isWritable = writable; return this; } public Builder setEnumerable(boolean enumerable) { isEnumerable = enumerable; return this; } public Builder setTransient(boolean aTransient) { this.isTransient = aTransient; return this; } private Builder setGetterOrSetterName(String name) { getterOrSetterName = name; return this; } public RemoteObjectNode build() { return new RemoteObjectNode(this); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectNodeRenderer.java
client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectNodeRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.treeview.NodeRenderer; import collide.client.treeview.TreeNodeElement; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectType; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.shared.util.StringUtils; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; import elemental.html.SpanElement; /** * Renders the {@link RemoteObjectNode} in the {@link RemoteObjectTree}. * */ public class RemoteObjectNodeRenderer implements NodeRenderer<RemoteObjectNode> { private static final RegExp LINE_BREAK_REGEXP = RegExp.compile("\\r?\\n", "g"); private static final String LINE_BREAK_SUBSTITUTE = "\u21B5"; public interface Css extends CssResource { String root(); String propertyName(); String separator(); String propertyValue(); String wasThrown(); String noPropertyValue(); String notEnumerable(); String tokenArray(); String tokenBoolean(); String tokenDate(); String tokenFunction(); String tokenNode(); String tokenNull(); String tokenNumber(); String tokenObject(); String tokenRegexp(); String tokenString(); String tokenUndefined(); String inPropertyValueMutation(); } interface Resources extends ClientBundle { @Source("RemoteObjectNodeRenderer.css") Css remoteObjectNodeRendererCss(); } private final Css css; RemoteObjectNodeRenderer(Resources resources) { css = resources.remoteObjectNodeRendererCss(); } @Override public Element getNodeKeyTextContainer(SpanElement treeNodeLabel) { return treeNodeLabel.getFirstChildElement(); } @Override public SpanElement renderNodeContents(RemoteObjectNode data) { SpanElement root = Elements.createSpanElement(css.root()); if (data.wasThrown()) { root.addClassName(css.wasThrown()); } Element propertyNameElement = Elements.createDivElement(css.propertyName()); if (data.getRemoteObject() == null) { propertyNameElement.addClassName(css.noPropertyValue()); } if (!data.isEnumerable()) { propertyNameElement.addClassName(css.notEnumerable()); } propertyNameElement.setTextContent(data.getName()); root.appendChild(propertyNameElement); String propertyValue = getPropertyValueAsString(data); if (!StringUtils.isNullOrEmpty(propertyValue)) { if (!StringUtils.isNullOrEmpty(data.getName())) { Element separator = Elements.createDivElement(css.separator()); separator.setTextContent(":"); root.appendChild(separator); } Element propertyValueElement = Elements.createDivElement(css.propertyValue(), getTokenClassName(data.getRemoteObject())); propertyValueElement.setTextContent(propertyValue); root.appendChild(propertyValueElement); } return root; } @Override public void updateNodeContents(TreeNodeElement<RemoteObjectNode> treeNode) { // Not implemented. } Element getPropertyValueElement(SpanElement treeNodeLabel) { return DomUtils.getFirstElementByClassName(treeNodeLabel, css.propertyValue()); } Element getAncestorPropertyNameElement(Element element) { return CssUtils.getAncestorOrSelfWithClassName(element, css.propertyName()); } Element getAncestorPropertyValueElement(Element element) { return CssUtils.getAncestorOrSelfWithClassName(element, css.propertyValue()); } void enterPropertyValueMutation(SpanElement treeNodeLabel) { treeNodeLabel.addClassName(css.inPropertyValueMutation()); } void exitPropertyValueMutation(SpanElement treeNodeLabel, String newLabel) { treeNodeLabel.removeClassName(css.inPropertyValueMutation()); Element propertyValueElement = getPropertyValueElement(treeNodeLabel); if (propertyValueElement != null) { propertyValueElement.setTextContent(StringUtils.nullToEmpty(newLabel)); } } void removeTokenClassName(RemoteObjectNode data, SpanElement treeNodeLabel) { Element propertyValueElement = getPropertyValueElement(treeNodeLabel); if (propertyValueElement != null) { String tokenClassName = getTokenClassName(data.getRemoteObject()); if (!StringUtils.isNullOrEmpty(tokenClassName)) { propertyValueElement.removeClassName(tokenClassName); } } } public String getTokenClassName(RemoteObject remoteObject) { if (remoteObject == null) { return ""; } if (remoteObject.getSubType() != null) { switch (remoteObject.getSubType()) { case ARRAY: return css.tokenArray(); case DATE: return css.tokenDate(); case NODE: return css.tokenNode(); case NULL: return css.tokenNull(); case REGEXP: return css.tokenRegexp(); } } if (remoteObject.getType() != null) { switch (remoteObject.getType()) { case BOOLEAN: return css.tokenBoolean(); case FUNCTION: return css.tokenFunction(); case NUMBER: return css.tokenNumber(); case OBJECT: return css.tokenObject(); case STRING: return css.tokenString(); case UNDEFINED: return css.tokenUndefined(); } } return ""; } private static String getPropertyValueAsString(RemoteObjectNode node) { RemoteObject remoteObject = node.getRemoteObject(); if (remoteObject == null) { return ""; } if (node.wasThrown()) { return "[Exception: " + remoteObject.getDescription() + "]"; } if (node.isTransient()) { // Just put some UI difference for the transient objects. return ""; } if (RemoteObjectType.STRING.equals(remoteObject.getType())) { return "\"" + LINE_BREAK_REGEXP.replace(remoteObject.getDescription(), LINE_BREAK_SUBSTITUTE) + "\""; } return remoteObject.getDescription(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarBreakpointsPane.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarBreakpointsPane.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.SortedList; import com.google.collide.shared.util.StringUtils; import com.google.common.annotations.VisibleForTesting; 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; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * UI component that displays all breakpoints set in the project. * * TODO: Text changes of the lines that have breakpoints should be * reflected in this UI pane. */ public class DebuggingSidebarBreakpointsPane extends UiComponent< DebuggingSidebarBreakpointsPane.View> { public interface Css extends CssResource { String root(); String section(); String sectionHeader(); String sectionFileName(); String sectionFilePath(); String breakpoint(); String breakpointIcon(); String breakpointInactive(); String breakpointLine(); String breakpointLineNumber(); } interface Resources extends ClientBundle { @Source("DebuggingSidebarBreakpointsPane.css") Css workspaceEditorDebuggingSidebarBreakpointsPaneCss(); @Source("file.png") DataResource fileImageResource(); @Source("breakpointActive.png") ImageResource breakpointActiveResource(); @Source("breakpointInactive.png") ImageResource breakpointInactiveResource(); } /** * Listener for the user clicks on the breakpoints. */ interface Listener { void onBreakpointIconClick(Breakpoint breakpoint); void onBreakpointLineClick(Breakpoint breakpoint); } static class View extends CompositeView<ViewEvents> { private final Css css; private final EventListener breakpointClickListener = new EventListener() { @Override public void handleEvent(Event evt) { Element target = (Element) evt.getTarget(); Element breakpoint = CssUtils.getAncestorOrSelfWithClassName(target, css.breakpoint()); Element section = CssUtils.getAncestorOrSelfWithClassName(breakpoint, css.section()); int breakpointIndex = DomUtils.getSiblingIndexWithClassName(breakpoint, css.breakpoint()); int sectionIndex = DomUtils.getSiblingIndexWithClassName(section, css.section()); if (target.hasClassName(css.breakpointIcon())) { getDelegate().onBreakpointIconClick(sectionIndex, breakpointIndex); } else { getDelegate().onBreakpointLineClick(sectionIndex, breakpointIndex); } } }; View(Resources resources) { css = resources.workspaceEditorDebuggingSidebarBreakpointsPaneCss(); Element rootElement = Elements.createDivElement(css.root()); setElement(rootElement); } @VisibleForTesting void addBreakpointSection(int sectionIndex) { getElement().insertBefore(createSection(), getSectionElement(sectionIndex)); } @VisibleForTesting void removeBreakpointSection(int sectionIndex) { getSectionElement(sectionIndex).removeFromParent(); } @VisibleForTesting void addBreakpoint(int sectionIndex, int breakpointIndex) { getSectionElement(sectionIndex).insertBefore(createBreakpoint(), getBreakpointElement(sectionIndex, breakpointIndex)); } @VisibleForTesting void removeBreakpoint(int sectionIndex, int breakpointIndex) { getBreakpointElement(sectionIndex, breakpointIndex).removeFromParent(); } private void updateBreakpointSection(int sectionIndex, String fileName, String path) { Element section = getSectionElement(sectionIndex); DomUtils.getFirstElementByClassName(section, css.sectionFileName()).setTextContent(fileName); DomUtils.getFirstElementByClassName(section, css.sectionFilePath()).setTextContent(path); } private void updateBreakpoint(int sectionIndex, int breakpointIndex, boolean active, String line, int lineNumber) { line = StringUtils.nullToEmpty(line).trim(); Element breakpoint = getBreakpointElement(sectionIndex, breakpointIndex); CssUtils.setClassNameEnabled(breakpoint, css.breakpointInactive(), !active); DomUtils.getFirstElementByClassName(breakpoint, css.breakpointLine()).setTextContent(line); // TODO: i18n? DomUtils.getFirstElementByClassName(breakpoint, css.breakpointLineNumber()) .setTextContent("line " + (lineNumber + 1)); // Set a tooltip. // TODO: Do we actually need this? String tooltip = line + " line " + (lineNumber + 1); breakpoint.setTitle(tooltip); } private String getBreakpointLineText(int sectionIndex, int breakpointIndex) { Element breakpoint = getBreakpointElement(sectionIndex, breakpointIndex); Element line = DomUtils.getFirstElementByClassName(breakpoint, css.breakpointLine()); return line.getTextContent(); } private Element createSection() { Element section = Elements.createDivElement(css.section()); // TODO: i18n? Element separator = Elements.createSpanElement(); separator.setInnerHTML("&mdash;"); Element sectionHeader = Elements.createDivElement(css.sectionHeader()); sectionHeader.appendChild(Elements.createSpanElement(css.sectionFileName())); sectionHeader.appendChild(separator); sectionHeader.appendChild(Elements.createSpanElement(css.sectionFilePath())); section.appendChild(sectionHeader); return section; } private Element createBreakpoint() { Element breakpoint = Elements.createDivElement(css.breakpoint()); breakpoint.appendChild(Elements.createDivElement(css.breakpointIcon())); breakpoint.appendChild(Elements.createSpanElement(css.breakpointLine())); breakpoint.appendChild(Elements.createSpanElement(css.breakpointLineNumber())); breakpoint.addEventListener(Event.CLICK, breakpointClickListener, false); return breakpoint; } private Element getSectionElement(int sectionIndex) { return DomUtils.getNthChildWithClassName(getElement(), sectionIndex, css.section()); } private Element getBreakpointElement(int sectionIndex, int breakpointIndex) { Element section = getSectionElement(sectionIndex); return DomUtils.getNthChildWithClassName(section, breakpointIndex, css.breakpoint()); } } /** * The view events. */ private interface ViewEvents { void onBreakpointIconClick(int sectionIndex, int breakpointIndex); void onBreakpointLineClick(int sectionIndex, int breakpointIndex); } static DebuggingSidebarBreakpointsPane create(View view) { return new DebuggingSidebarBreakpointsPane(view); } private static final SortedList.Comparator<Breakpoint> SORTING_FUNCTION = new SortedList.Comparator<Breakpoint>() { @Override public int compare(Breakpoint a, Breakpoint b) { int result = a.getPath().compareTo(b.getPath()); if (result != 0) { return result; } return a.getLineNumber() - b.getLineNumber(); } }; private Listener delegateListener; private final SortedList<Breakpoint> breakpoints = new SortedList<Breakpoint>(SORTING_FUNCTION); private final JsonArray<Integer> breakpointCountBySections = JsonCollections.createArray(); private final class ViewEventsImpl implements ViewEvents { @Override public void onBreakpointIconClick(int sectionIndex, int breakpointIndex) { Breakpoint breakpoint = getBreakpoint(sectionIndex, breakpointIndex); if (breakpoint == null) { Log.error(getClass(), "Failed to find a breakpoint at " + sectionIndex + ":" + breakpointIndex); return; } if (delegateListener != null) { delegateListener.onBreakpointIconClick(breakpoint); } } @Override public void onBreakpointLineClick(int sectionIndex, int breakpointIndex) { Breakpoint breakpoint = getBreakpoint(sectionIndex, breakpointIndex); if (breakpoint == null) { Log.error(getClass(), "Failed to find a breakpoint at " + sectionIndex + ":" + breakpointIndex); return; } if (delegateListener != null) { delegateListener.onBreakpointLineClick(breakpoint); } } } @VisibleForTesting DebuggingSidebarBreakpointsPane(View view) { super(view); view.setDelegate(new ViewEventsImpl()); } void setListener(Listener listener) { delegateListener = listener; } void addBreakpoint(Breakpoint breakpoint) { int index = breakpoints.add(breakpoint); int section = -1; int breakpointCount = 0; while (breakpointCount < index && section + 1 < breakpointCountBySections.size()) { ++section; breakpointCount += breakpointCountBySections.get(section); } // Now, the breakpoint can be inserted into the following sections: // 1) {@code section}, if it exists and should contain the new breakpoint // 2) {@code section + 1}, if it exists and should contain the new breakpoint // 3) A new section int breakpointIndexInSection; if (index > 0 && breakpoint.getPath().compareTo(breakpoints.get(index - 1).getPath()) == 0) { int num = breakpointCountBySections.get(section); breakpointCountBySections.set(section, num + 1); breakpointIndexInSection = index - breakpointCount + num; } else if (index + 1 < breakpoints.size() && breakpoint.getPath().compareTo(breakpoints.get(index + 1).getPath()) == 0) { ++section; int num = breakpointCountBySections.get(section); breakpointCountBySections.set(section, num + 1); breakpointIndexInSection = index - breakpointCount; } else { ++section; breakpointCountBySections.splice(section, 0, 1); breakpointIndexInSection = 0; getView().addBreakpointSection(section); getView().updateBreakpointSection(section, breakpoint.getPath().getBaseName(), PathUtil.createExcludingLastN(breakpoint.getPath(), 1).getPathString()); } getView().addBreakpoint(section, breakpointIndexInSection); getView().updateBreakpoint(section, breakpointIndexInSection, breakpoint.isActive(), "", breakpoint.getLineNumber()); } void removeBreakpoint(Breakpoint breakpoint) { int index = breakpoints.findIndex(breakpoint); if (index < 0) { Log.error(getClass(), "Failed to remove a breakpoint: " + breakpoint); return; } breakpoints.remove(index); Position position = getBreakpointPosition(index); int section = position.sectionIndex; int breakpointsInSection = breakpointCountBySections.get(section); getView().removeBreakpoint(section, position.breakpointIndex); if (breakpointsInSection > 1) { breakpointCountBySections.set(section, breakpointsInSection - 1); } else { breakpointCountBySections.splice(section, 1); getView().removeBreakpointSection(section); } } void updateBreakpoint(Breakpoint breakpoint, String line) { int index = breakpoints.findIndex(breakpoint); if (index < 0) { Log.error(getClass(), "Failed to update a breakpoint: " + breakpoint); return; } Position position = getBreakpointPosition(index); getView().updateBreakpoint(position.sectionIndex, position.breakpointIndex, breakpoint.isActive(), line, breakpoint.getLineNumber()); } boolean hasBreakpoint(Breakpoint breakpoint) { return breakpoints.findIndex(breakpoint) >= 0; } String getBreakpointLineText(Breakpoint breakpoint) { int index = breakpoints.findIndex(breakpoint); if (index < 0) { Log.error(getClass(), "Failed to find a breakpoint: " + breakpoint); return ""; } Position position = getBreakpointPosition(index); return getView().getBreakpointLineText(position.sectionIndex, position.breakpointIndex); } int getBreakpointCount() { return breakpoints.size(); } private Position getBreakpointPosition(int index) { int section = -1; int breakpointCount = 0; while (breakpointCount <= index && section + 1 < breakpointCountBySections.size()) { ++section; breakpointCount += breakpointCountBySections.get(section); } int breakpointsInSection = breakpointCountBySections.get(section); int breakpointIndexInSection = index - breakpointCount + breakpointsInSection; return new Position(section, breakpointIndexInSection); } private Breakpoint getBreakpoint(int sectionIndex, int breakpointIndex) { int index = breakpointIndex; for (int i = 0; i < sectionIndex; ++i) { index += breakpointCountBySections.get(i); } return breakpoints.get(index); } private static class Position { private final int sectionIndex; private final int breakpointIndex; private Position(int sectionIndex, int breakpointIndex) { this.sectionIndex = sectionIndex; this.breakpointIndex = breakpointIndex; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/AnchoredExecutionLine.java
client/src/main/java/com/google/collide/client/code/debugging/AnchoredExecutionLine.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.util.Elements; import com.google.collide.client.editor.Editor; import com.google.collide.client.testing.DebugAttributeSetter; 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 elemental.dom.Element; /** * Handles an <i>execution line</i> anchored into a document. * * <p>Execution line is a line in a script where debugger stopped. Each call * frame in the call stack has exactly one execution line, and execution line * of the topmost call frame is where the debugger stopped last. * */ class AnchoredExecutionLine { private static final AnchorType EXECUTION_LINE_ANCHOR_TYPE = AnchorType.create( AnchoredExecutionLine.class, "executionLine"); static AnchoredExecutionLine create(Editor editor, int lineNumber, String bufferLineClassName, String gutterLineClassName) { return new AnchoredExecutionLine(editor, lineNumber, bufferLineClassName, gutterLineClassName); } private final Editor editor; private final Document document; private final Anchor lineExecutionAnchor; private final Element bufferExecutionLine; private final Element gutterExecutionLine; private AnchoredExecutionLine(Editor editor, int lineNumber, String bufferLineClassName, String gutterLineClassName) { this.editor = editor; document = editor.getDocument(); lineExecutionAnchor = createExecutionLineAnchor(document, lineNumber); bufferExecutionLine = Elements.createDivElement(bufferLineClassName); new DebugAttributeSetter().add("linenumber", String.valueOf(lineNumber + 1)).on( bufferExecutionLine); editor.getBuffer().addAnchoredElement(lineExecutionAnchor, bufferExecutionLine); gutterExecutionLine = Elements.createDivElement(gutterLineClassName); new DebugAttributeSetter().add("linenumber", String.valueOf(lineNumber + 1)).on( gutterExecutionLine); editor.getLeftGutter().addAnchoredElement(lineExecutionAnchor, gutterExecutionLine); } void teardown() { editor.getBuffer().removeAnchoredElement(lineExecutionAnchor, bufferExecutionLine); editor.getLeftGutter().removeAnchoredElement(lineExecutionAnchor, gutterExecutionLine); document.getAnchorManager().removeAnchor(lineExecutionAnchor); } private static Anchor createExecutionLineAnchor(Document document, int lineNumber) { LineInfo lineInfo = document.getLineFinder().findLine(lineNumber); Anchor anchor = document.getAnchorManager().createAnchor(EXECUTION_LINE_ANCHOR_TYPE, lineInfo.line(), lineInfo.number(), AnchorManager.IGNORE_COLUMN); anchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); return anchor; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggingModel.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingModel.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * The model for the debugging info, such as breakpoints and etc. */ public class DebuggingModel { /** * Callback interface for getting notified about changes to the debugging * model that have been applied by a controller. */ public interface DebuggingModelChangeListener { /** * Notification that a breakpoint was added. */ void onBreakpointAdded(Breakpoint newBreakpoint); /** * Notification that a breakpoint was removed. */ void onBreakpointRemoved(Breakpoint oldBreakpoint); /** * Notification that a breakpoint was replaced. */ void onBreakpointReplaced(Breakpoint oldBreakpoint, Breakpoint newBreakpoint); /** * Notification that the Pause-On-Exceptions mode was changed. */ void onPauseOnExceptionsModeUpdated(PauseOnExceptionsMode oldMode, PauseOnExceptionsMode newMode); /** * Notification that the breakpoints-enabled flag was changed. */ void onBreakpointsEnabledUpdated(boolean newValue); } private interface ChangeDispatcher { void dispatch(DebuggingModelChangeListener changeListener); } /** * Pause-On-Exceptions modes. Tells the debugger what to do if an exception is fired. */ public enum PauseOnExceptionsMode { NONE, ALL, UNCAUGHT } private final JsonArray<DebuggingModelChangeListener> modelChangeListeners = JsonCollections.createArray(); private final JsonArray<Breakpoint> breakpoints = JsonCollections.createArray(); private PauseOnExceptionsMode pauseOnExceptionsMode = PauseOnExceptionsMode.NONE; private boolean breakpointsEnabled = true; public DebuggingModel() { Log.debug(getClass(), "Creating DebuggingModel."); } /** * Adds a {@link DebuggingModelChangeListener} to be notified of mutations applied * by a controller to the underlying debugging model. * * @param modelChangeListener the listener we are adding */ public void addModelChangeListener(DebuggingModelChangeListener modelChangeListener) { modelChangeListeners.add(modelChangeListener); } /** * Removes a {@link DebuggingModelChangeListener} from the set of listeners * subscribed to model changes. * * @param modelChangeListener the listener we are removing */ public void removeModelChangeListener(DebuggingModelChangeListener modelChangeListener) { modelChangeListeners.remove(modelChangeListener); } /** * Adds a breakpoint to the debugging model. */ public void addBreakpoint(final Breakpoint breakpoint) { Log.debug(getClass(), "Adding " + breakpoint); if (!breakpoints.contains(breakpoint)) { breakpoints.add(breakpoint); dispatchModelChange(new ChangeDispatcher() { @Override public void dispatch(DebuggingModelChangeListener changeListener) { changeListener.onBreakpointAdded(breakpoint); } }); } } /** * Removes a breakpoint from the debugging model. */ public void removeBreakpoint(final Breakpoint breakpoint) { Log.debug(getClass(), "Removing " + breakpoint); if (breakpoints.remove(breakpoint)) { dispatchModelChange(new ChangeDispatcher() { @Override public void dispatch(DebuggingModelChangeListener changeListener) { changeListener.onBreakpointRemoved(breakpoint); } }); } } /** * Updates a breakpoint from the debugging model. */ public void updateBreakpoint(final Breakpoint oldBreakpoint, final Breakpoint newBreakpoint) { Log.debug(getClass(), "Updating " + oldBreakpoint + " - to - " + newBreakpoint); if (oldBreakpoint.equals(newBreakpoint)) { return; // Nothing to do. } if (breakpoints.contains(oldBreakpoint)) { if (breakpoints.contains(newBreakpoint)) { removeBreakpoint(oldBreakpoint); return; } breakpoints.remove(oldBreakpoint); breakpoints.add(newBreakpoint); dispatchModelChange(new ChangeDispatcher() { @Override public void dispatch(DebuggingModelChangeListener changeListener) { changeListener.onBreakpointReplaced(oldBreakpoint, newBreakpoint); } }); } } /** * Sets the Pause-On-Exceptions mode. */ public void setPauseOnExceptionsMode(PauseOnExceptionsMode mode) { Log.debug(getClass(), "Setting pause-on-exceptions " + mode); if (!pauseOnExceptionsMode.equals(mode)) { final PauseOnExceptionsMode oldMode = pauseOnExceptionsMode; final PauseOnExceptionsMode newMode = mode; pauseOnExceptionsMode = mode; dispatchModelChange(new ChangeDispatcher() { @Override public void dispatch(DebuggingModelChangeListener changeListener) { changeListener.onPauseOnExceptionsModeUpdated(oldMode, newMode); } }); } } /** * Enables or disables all breakpoints. */ public void setBreakpointsEnabled(boolean value) { Log.debug(getClass(), "Setting enable-breakpoints to " + value); if (breakpointsEnabled != value) { breakpointsEnabled = value; dispatchModelChange(new ChangeDispatcher() { @Override public void dispatch(DebuggingModelChangeListener changeListener) { changeListener.onBreakpointsEnabledUpdated(breakpointsEnabled); } }); } } /** * @return copy of all breakpoints in the given workspace */ public JsonArray<Breakpoint> getBreakpoints() { return breakpoints.copy(); } public int getBreakpointCount() { return breakpoints.size(); } public PauseOnExceptionsMode getPauseOnExceptionsMode() { return pauseOnExceptionsMode; } public boolean isBreakpointsEnabled() { return breakpointsEnabled; } private void dispatchModelChange(ChangeDispatcher dispatcher) { JsonArray<DebuggingModelChangeListener> copy = modelChangeListeners.copy(); for (int i = 0, n = copy.size(); i < n; i++) { dispatcher.dispatch(copy.get(i)); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/AnchoredBreakpoints.java
client/src/main/java/com/google/collide/client/code/debugging/AnchoredBreakpoints.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import java.util.Comparator; import com.google.collide.client.util.ScheduledCommandExecutor; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.TextChange; 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.document.anchor.AnchorUtils; import com.google.collide.shared.util.JsonCollections; /** * Handles an array of breakpoints anchored into a {@link Document}. */ class AnchoredBreakpoints { private static final AnchorType BREAKPOINT_ANCHOR_TYPE = AnchorType.create( AnchoredBreakpoints.class, "breakpoint"); /** * A listener that is called when a line that has a breakpoint set on it * changes. */ public interface BreakpointDescriptionListener { void onBreakpointDescriptionChange(Breakpoint breakpoint, String newText); } private static final Comparator<Anchor> anchorComparator = new Comparator<Anchor>() { @Override public int compare(Anchor o1, Anchor o2) { Breakpoint b1 = o1.getValue(); Breakpoint b2 = o2.getValue(); return b1.getLineNumber() - b2.getLineNumber(); } }; private abstract static class AnchorBatchCommandExecutor extends ScheduledCommandExecutor { private JsonArray<Anchor> updatedAnchors = JsonCollections.createArray(); @Override protected final void execute() { if (updatedAnchors.isEmpty()) { return; } JsonArray<Anchor> anchors = updatedAnchors; updatedAnchors = JsonCollections.createArray(); executeBatchCommand(anchors); } protected abstract void executeBatchCommand(JsonArray<Anchor> anchors); public void addAnchor(Anchor anchor) { if (BREAKPOINT_ANCHOR_TYPE.equals(anchor.getType()) && !updatedAnchors.contains(anchor)) { updatedAnchors.add(anchor); scheduleDeferred(); } } public void removeAnchor(Anchor anchor) { updatedAnchors.remove(anchor); } public void teardown() { updatedAnchors.clear(); cancel(); } } private final AnchorBatchCommandExecutor anchorsLineShiftedCommand = new AnchorBatchCommandExecutor() { @Override protected void executeBatchCommand(JsonArray<Anchor> anchors) { applyMovedAnchors(anchors); } }; private final Anchor.ShiftListener anchorShiftListener = new Anchor.ShiftListener() { @Override public void onAnchorShifted(Anchor anchor) { anchorsLineShiftedCommand.addAnchor(anchor); } }; private final AnchorBatchCommandExecutor anchorChangedCommand = new AnchorBatchCommandExecutor() { @Override protected void executeBatchCommand(JsonArray<Anchor> anchors) { applyUpdatedAnchors(anchors); } }; /** * Listener of the document text changes to track breakpoint descriptions. */ private class TextListenerImpl implements Document.TextListener, AnchorManager.AnchorVisitor { @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { for (int i = 0, n = textChanges.size(); i < n; ++i) { TextChange textChange = textChanges.get(i); Line line = textChange.getLine(); Line stopAtLine = textChange.getEndLine().getNextLine(); while (line != stopAtLine) { AnchorUtils.visitAnchorsOnLine(line, this); line = line.getNextLine(); } } } @Override public void visitAnchor(Anchor anchor) { anchorChangedCommand.addAnchor(anchor); } } private final Document document; private final DebuggingModel debuggingModel; private final JsonArray<Breakpoint> breakpoints = JsonCollections.createArray(); private final JsonArray<Anchor> anchors = JsonCollections.createArray(); private final Document.TextListener documentTextListener = new TextListenerImpl(); private BreakpointDescriptionListener breakpointDescriptionListener; AnchoredBreakpoints(DebuggingModel debuggingModel, Document document) { this.debuggingModel = debuggingModel; this.document = document; } void teardown() { document.getTextListenerRegistrar().remove(documentTextListener); for (int i = 0, n = anchors.size(); i < n; ++i) { detachAnchor(anchors.get(i)); } breakpoints.clear(); anchors.clear(); anchorsLineShiftedCommand.teardown(); anchorChangedCommand.teardown(); breakpointDescriptionListener = null; } public void setBreakpointDescriptionListener(BreakpointDescriptionListener listener) { this.breakpointDescriptionListener = listener; } public Anchor anchorBreakpoint(Breakpoint breakpoint) { LineInfo lineInfo = document.getLineFinder().findLine(breakpoint.getLineNumber()); Anchor anchor = document.getAnchorManager().createAnchor(BREAKPOINT_ANCHOR_TYPE, lineInfo.line(), lineInfo.number(), AnchorManager.IGNORE_COLUMN); anchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); anchor.setValue(breakpoint); anchor.getShiftListenerRegistrar().add(anchorShiftListener); if (anchors.isEmpty()) { document.getTextListenerRegistrar().add(documentTextListener); } breakpoints.add(breakpoint); anchors.add(anchor); return anchor; } public boolean removeBreakpoint(Breakpoint breakpoint) { for (int i = 0, n = breakpoints.size(); i < n; ++i) { if (breakpoint.equals(breakpoints.get(i))) { detachAnchor(anchors.get(i)); breakpoints.remove(i); anchors.remove(i); if (anchors.isEmpty()) { document.getTextListenerRegistrar().remove(documentTextListener); } return true; } } return false; } public boolean contains(Breakpoint breakpoint) { return breakpoints.contains(breakpoint); } public Breakpoint get(int index) { return breakpoints.get(index); } public int size() { return breakpoints.size(); } private void detachAnchor(Anchor anchor) { document.getAnchorManager().removeAnchor(anchor); anchorsLineShiftedCommand.removeAnchor(anchor); anchorChangedCommand.removeAnchor(anchor); anchor.setValue(null); anchor.getShiftListenerRegistrar().remove(anchorShiftListener); } private void applyMovedAnchors(JsonArray<Anchor> anchors) { // We have to determine what breakpoint to move first in case if we have a // few consecutive breakpoints set. For example, if we have breakpoints at // lines 3,4,5, and we insert a new line at the beginning of the document, // then we should start updating the breakpoints from the end: // 5->6, 4->5, 3->4, so that not to mess up with the original breakpoints. // Below is a simple strategy to ensure the correct iteration order in most // cases (when all breakpoints move in the same direction). In those rare // cases when we might loose some breakpoints (for example, due to // collaborative editing), we consider this tolerable. anchors.sort(anchorComparator); int deltaSum = 0; for (int i = 0, n = anchors.size(); i < n; ++i) { Anchor anchor = anchors.get(i); Breakpoint breakpoint = anchor.getValue(); deltaSum += anchor.getLineNumber() - breakpoint.getLineNumber(); } for (int i = 0, n = anchors.size(); i < n; ++i) { Anchor anchor = anchors.get(deltaSum < 0 ? i : n - 1 - i); Breakpoint oldBreakpoint = anchor.getValue(); Breakpoint newBreakpoint = new Breakpoint.Builder(oldBreakpoint) .setLineNumber(anchor.getLineNumber()) .build(); debuggingModel.updateBreakpoint(oldBreakpoint, newBreakpoint); } } private void applyUpdatedAnchors(JsonArray<Anchor> anchors) { if (breakpointDescriptionListener == null) { return; } for (int i = 0, n = anchors.size(); i < n; ++i) { Anchor anchor = anchors.get(i); Breakpoint breakpoint = anchor.getValue(); String newText = anchor.getLine().getText(); breakpointDescriptionListener.onBreakpointDescriptionChange(breakpoint, newText); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggerState.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggerState.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import javax.annotation.Nullable; import com.google.collide.client.code.debugging.DebuggerApi.DebuggerResponseListener; import com.google.collide.client.code.debugging.DebuggerApiTypes.BreakpointInfo; import com.google.collide.client.code.debugging.DebuggerApiTypes.CallFrame; import com.google.collide.client.code.debugging.DebuggerApiTypes.ConsoleMessage; import com.google.collide.client.code.debugging.DebuggerApiTypes.Location; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnAllCssStyleSheetsResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnBreakpointResolvedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnEvaluateExpressionResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnPausedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnRemoteObjectPropertiesResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnRemoteObjectPropertyChanged; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnScriptParsedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectId; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.ScheduledCommandExecutor; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.StringUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.gwt.core.client.GWT; /** * Represents debugger state on a given debugger session: whether debugger is * active, running or paused, and etc. * * <p>This class also contains cached data responses from the debugger for the * life time of a debugger session. */ class DebuggerState { /** * Listener of the "debugger is available" state changes. */ interface DebuggerAvailableListener { void onDebuggerAvailableChange(); } /** * Listener of the debugger state changes. */ interface DebuggerStateListener { void onDebuggerStateChange(); } /** * Listener of the {@link DebuggerApiTypes.RemoteObject} related changes. */ interface RemoteObjectListener { void onRemoteObjectPropertiesResponse(OnRemoteObjectPropertiesResponse response); void onRemoteObjectPropertyChanged(OnRemoteObjectPropertyChanged response); } /** * Listener of the expression evaluation responses. */ interface EvaluateExpressionListener { void onEvaluateExpressionResponse(OnEvaluateExpressionResponse response); void onGlobalObjectChanged(); } /** * Listener of the CSS related responses. */ interface CssListener { void onAllCssStyleSheetsResponse(OnAllCssStyleSheetsResponse response); } /** * Listener of the Console related events. */ interface ConsoleListener { void onConsoleMessage(ConsoleMessage message); void onConsoleMessageRepeatCountUpdated(ConsoleMessage message, int repeatCount); void onConsoleMessagesCleared(); } /** * Listener of the custom message responses. */ interface CustomMessageListener { void onCustomMessageResponse(String response); } private final String sessionId; private final DebuggerApi debuggerApi; private final JsonArray<BreakpointInfoImpl> breakpointInfos = JsonCollections.createArray(); private JsonStringMap<OnScriptParsedResponse> scriptParsedResponses = JsonCollections.createMap(); private final ListenerManager<DebuggerAvailableListener> debuggerAvailableListenerManager; private final ListenerManager<DebuggerStateListener> debuggerStateListenerManager; private final ListenerManager<RemoteObjectListener> remoteObjectListenerManager; private final ListenerManager<EvaluateExpressionListener> evaluateExpressionListenerManager; private final ListenerManager<CssListener> cssListenerManager; private final ListenerManager<ConsoleListener> consoleListenerManager; private final ListenerManager<CustomMessageListener> customMessageListenerManager; private final JsonStringSet expressionsToEvaluate = JsonCollections.createStringSet(); private boolean active; private SourceMapping sourceMapping; @Nullable private OnPausedResponse lastOnPausedResponse; private final ScheduledCommandExecutor expressionsEvaluateCommand = new ScheduledCommandExecutor() { @Override protected void execute() { JsonArray<String> expressions = expressionsToEvaluate.getKeys(); expressionsToEvaluate.clear(); for (int i = 0, n = expressions.size(); i < n; ++i) { sendEvaluateExpressionRequest(expressions.get(i)); } } }; /** * Index of the active {@link CallFrame} in the call stack. * * <p>Default value is {@code 0} that corresponds to the topmost * {@link CallFrame} where debugger has stopped. If debugger is not paused, * this value has no meaning. * * <p>This is controlled by the user from the Debugger Sidebar UI. */ private int activeCallFrameIndex = 0; /** * Last console message received from the debugger. */ private ConsoleMessage lastConsoleMessage; private final DebuggerResponseListener debuggerResponseListener = new DebuggerResponseListener() { @Override public void onDebuggerAvailableChanged() { debuggerAvailableListenerManager.dispatch(DEBUGGER_AVAILABLE_DISPATCHER); } @Override public void onDebuggerAttached(String eventSessionId) { if (sessionId.equals(eventSessionId)) { setActive(true); } } @Override public void onDebuggerDetached(String eventSessionId) { if (sessionId.equals(eventSessionId)) { setActive(false); } } @Override public void onBreakpointResolved(String eventSessionId, OnBreakpointResolvedResponse response) { if (sessionId.equals(eventSessionId)) { updateBreakpointInfo(response); } } @Override public void onBreakpointRemoved(String eventSessionId, String breakpointId) { if (sessionId.equals(eventSessionId)) { removeBreakpointById(breakpointId); } } @Override public void onPaused(String eventSessionId, OnPausedResponse response) { if (sessionId.equals(eventSessionId)) { setOnPausedResponse(response); } } @Override public void onResumed(String eventSessionId) { if (sessionId.equals(eventSessionId)) { setOnPausedResponse(null); } } @Override public void onScriptParsed(String eventSessionId, OnScriptParsedResponse response) { if (sessionId.equals(eventSessionId)) { scriptParsedResponses.put(response.getScriptId(), response); } } @Override public void onRemoteObjectPropertiesResponse(String eventSessionId, final OnRemoteObjectPropertiesResponse response) { if (sessionId.equals(eventSessionId)) { remoteObjectListenerManager.dispatch(new Dispatcher<RemoteObjectListener>() { @Override public void dispatch(RemoteObjectListener listener) { listener.onRemoteObjectPropertiesResponse(response); } }); } } @Override public void onRemoteObjectPropertyChanged(String eventSessionId, final OnRemoteObjectPropertyChanged response) { if (sessionId.equals(eventSessionId)) { remoteObjectListenerManager.dispatch(new Dispatcher<RemoteObjectListener>() { @Override public void dispatch(RemoteObjectListener listener) { listener.onRemoteObjectPropertyChanged(response); } }); } } @Override public void onEvaluateExpressionResponse(String eventSessionId, final OnEvaluateExpressionResponse response) { if (sessionId.equals(eventSessionId)) { CallFrame callFrame = getActiveCallFrame(); String callFrameId = (callFrame == null ? null : callFrame.getId()); if (!StringUtils.equalStringsOrEmpty(callFrameId, response.getCallFrameId())) { // Maybe a late response from a previous evaluation call. The corresponding evaluation // call for the active call frame should have been already sent to the debugger, so just // ignore this old response and wait for the actual one. return; } evaluateExpressionListenerManager.dispatch(new Dispatcher<EvaluateExpressionListener>() { @Override public void dispatch(EvaluateExpressionListener listener) { listener.onEvaluateExpressionResponse(response); } }); } } @Override public void onGlobalObjectChanged(String eventSessionId) { if (sessionId.equals(eventSessionId)) { evaluateExpressionListenerManager.dispatch(new Dispatcher<EvaluateExpressionListener>() { @Override public void dispatch(EvaluateExpressionListener listener) { listener.onGlobalObjectChanged(); } }); } } @Override public void onAllCssStyleSheetsResponse(String eventSessionId, final OnAllCssStyleSheetsResponse response) { if (sessionId.equals(eventSessionId)) { cssListenerManager.dispatch(new Dispatcher<CssListener>() { @Override public void dispatch(CssListener listener) { listener.onAllCssStyleSheetsResponse(response); } }); } } @Override public void onConsoleMessage(String eventSessionId, ConsoleMessage message) { if (sessionId.equals(eventSessionId)) { lastConsoleMessage = message; consoleListenerManager.dispatch(new Dispatcher<ConsoleListener>() { @Override public void dispatch(ConsoleListener listener) { listener.onConsoleMessage(lastConsoleMessage); } }); } } @Override public void onConsoleMessageRepeatCountUpdated(String eventSessionId, final int repeatCount) { if (sessionId.equals(eventSessionId) && lastConsoleMessage != null) { consoleListenerManager.dispatch(new Dispatcher<ConsoleListener>() { @Override public void dispatch(ConsoleListener listener) { listener.onConsoleMessageRepeatCountUpdated(lastConsoleMessage, repeatCount); } }); } } @Override public void onConsoleMessagesCleared(String eventSessionId) { if (sessionId.equals(eventSessionId)) { lastConsoleMessage = null; consoleListenerManager.dispatch(CONSOLE_MESSAGES_CLEARED_DISPATCHER); } } @Override public void onCustomMessageResponse(String eventSessionId, final String response) { if (sessionId.equals(eventSessionId)) { customMessageListenerManager.dispatch(new Dispatcher<CustomMessageListener>() { @Override public void dispatch(CustomMessageListener listener) { listener.onCustomMessageResponse(response); } }); } } }; private static final Dispatcher<DebuggerStateListener> DEBUGGER_STATE_DISPATCHER = new Dispatcher<DebuggerStateListener>() { @Override public void dispatch(DebuggerStateListener listener) { listener.onDebuggerStateChange(); } }; private static final Dispatcher<DebuggerAvailableListener> DEBUGGER_AVAILABLE_DISPATCHER = new Dispatcher<DebuggerAvailableListener>() { @Override public void dispatch(DebuggerAvailableListener listener) { listener.onDebuggerAvailableChange(); } }; private static final Dispatcher<ConsoleListener> CONSOLE_MESSAGES_CLEARED_DISPATCHER = new Dispatcher<ConsoleListener>() { @Override public void dispatch(ConsoleListener listener) { listener.onConsoleMessagesCleared(); } }; static DebuggerState create(String sessionId) { return new DebuggerState(sessionId, GWT.<DebuggerApi>create(DebuggerApi.class)); } @VisibleForTesting static DebuggerState createForTest(String sessionId, DebuggerApi debuggerApi) { return new DebuggerState(sessionId, debuggerApi); } private DebuggerState(String sessionId, DebuggerApi debuggerApi) { this.sessionId = sessionId; this.debuggerApi = debuggerApi; this.debuggerAvailableListenerManager = ListenerManager.create(); this.debuggerStateListenerManager = ListenerManager.create(); this.remoteObjectListenerManager = ListenerManager.create(); this.evaluateExpressionListenerManager = ListenerManager.create(); this.cssListenerManager = ListenerManager.create(); this.consoleListenerManager = ListenerManager.create(); this.customMessageListenerManager = ListenerManager.create(); this.debuggerApi.addDebuggerResponseListener(debuggerResponseListener); } ListenerRegistrar<DebuggerAvailableListener> getDebuggerAvailableListenerRegistrar() { return debuggerAvailableListenerManager; } ListenerRegistrar<DebuggerStateListener> getDebuggerStateListenerRegistrar() { return debuggerStateListenerManager; } ListenerRegistrar<RemoteObjectListener> getRemoteObjectListenerRegistrar() { return remoteObjectListenerManager; } ListenerRegistrar<EvaluateExpressionListener> getEvaluateExpressionListenerRegistrar() { return evaluateExpressionListenerManager; } ListenerRegistrar<CssListener> getCssListenerRegistrar() { return cssListenerManager; } ListenerRegistrar<ConsoleListener> getConsoleListenerRegistrar() { return consoleListenerManager; } ListenerRegistrar<CustomMessageListener> getCustomMessageListenerRegistrar() { return customMessageListenerManager; } /** * @return whether debugger is available to use */ public boolean isDebuggerAvailable() { return debuggerApi.isDebuggerAvailable(); } /** * @return URL of the browser extension that provides the debugging API, * or {@code null} if no such extension is available */ public String getDebuggingExtensionUrl() { return debuggerApi.getDebuggingExtensionUrl(); } /** * @return whether debugger is currently in use */ public boolean isActive() { return active; } /** * @return {@code true} if debugger is currently paused, otherwise debugger * is either not active or running */ public boolean isPaused() { return lastOnPausedResponse != null; } /** * Sets the index of the active {@link CallFrame} (i.e. selected by the user * in the UI). * * @param index index of the active call frame */ public void setActiveCallFrameIndex(int index) { activeCallFrameIndex = index; } /** * @return current {@link SourceMapping} object used for debugging, or * {@code null} if debugger is not active */ public SourceMapping getSourceMapping() { return sourceMapping; } /** * @return last {@link OnPausedResponse} from the debugger, or {@code null} * if debugger is not currently paused */ @Nullable public OnPausedResponse getOnPausedResponse() { return lastOnPausedResponse; } /** * @return {@link OnScriptParsedResponse} for a given source ID, or * {@code null} if undefined */ public OnScriptParsedResponse getOnScriptParsedResponse(String scriptId) { return scriptParsedResponses.get(scriptId); } public CallFrame getActiveCallFrame() { if (lastOnPausedResponse == null) { return null; } return lastOnPausedResponse.getCallFrames().get(activeCallFrameIndex); } /** * Calculates {@link PathUtil} for the active call frame of the current * debugger call stack. * * @return a new instance of {@code PathUtil} if the call frame points to a * script in a resource, served by the Collide server, or * {@code null} if this script is served elsewhere, or is anonymous * (result of an {@code eval()} call and etc.), or for other reasons */ public PathUtil getActiveCallFramePath() { CallFrame callFrame = getActiveCallFrame(); if (callFrame == null || callFrame.getLocation() == null) { return null; } Preconditions.checkNotNull(sourceMapping, "No source mapping!"); Preconditions.checkNotNull(scriptParsedResponses, "No parsed scripts!"); String scriptId = callFrame.getLocation().getScriptId(); return sourceMapping.getLocalScriptPath(scriptParsedResponses.get(scriptId)); } public int getActiveCallFrameExecutionLineNumber() { CallFrame callFrame = getActiveCallFrame(); if (callFrame == null || callFrame.getLocation() == null) { return -1; } Preconditions.checkNotNull(sourceMapping, "No source mapping!"); Preconditions.checkNotNull(scriptParsedResponses, "No parsed scripts!"); String scriptId = callFrame.getLocation().getScriptId(); return sourceMapping.getLocalSourceLineNumber(scriptParsedResponses.get(scriptId), callFrame.getLocation()); } void runDebugger(SourceMapping sourceMapping, String absoluteResourceUri) { Preconditions.checkNotNull(sourceMapping, "Source mapping is NULL!"); if (active) { // We will be reusing current debuggee session, so do a soft reset here. softReset(); } else { reset(); } active = true; this.sourceMapping = sourceMapping; lastOnPausedResponse = null; activeCallFrameIndex = 0; debuggerApi.runDebugger(sessionId, absoluteResourceUri); debuggerStateListenerManager.dispatch(DEBUGGER_STATE_DISPATCHER); } void shutdown() { debuggerApi.shutdownDebugger(sessionId); } void pause() { if (active) { debuggerApi.pause(sessionId); } } void resume() { if (active) { debuggerApi.resume(sessionId); } } void stepInto() { if (active) { debuggerApi.stepInto(sessionId); } } void stepOut() { if (active) { debuggerApi.stepOut(sessionId); } } void stepOver() { if (active) { debuggerApi.stepOver(sessionId); } } void requestRemoteObjectProperties(RemoteObjectId remoteObjectId) { if (active) { debuggerApi.requestRemoteObjectProperties(sessionId, remoteObjectId); } } void setRemoteObjectProperty(RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { if (active) { CallFrame callFrame = getActiveCallFrame(); if (callFrame != null) { debuggerApi.setRemoteObjectPropertyEvaluatedOnCallFrame( sessionId, callFrame, remoteObjectId, propertyName, propertyValueExpression); } else { debuggerApi.setRemoteObjectProperty( sessionId, remoteObjectId, propertyName, propertyValueExpression); } } } void removeRemoteObjectProperty(RemoteObjectId remoteObjectId, String propertyName) { if (active) { debuggerApi.removeRemoteObjectProperty(sessionId, remoteObjectId, propertyName); } } void renameRemoteObjectProperty(RemoteObjectId remoteObjectId, String oldName, String newName) { if (active) { debuggerApi.renameRemoteObjectProperty(sessionId, remoteObjectId, oldName, newName); } } /** * Evaluates a given expression either on the active {@link CallFrame} if the * debugger is currently paused, or on the global object if it is running. * * @param expression expression to evaluate */ void evaluateExpression(String expression) { if (active) { // Schedule-finally the evaluations to remove duplicates. expressionsToEvaluate.add(expression); expressionsEvaluateCommand.scheduleFinally(); } } private void sendEvaluateExpressionRequest(String expression) { if (active) { CallFrame callFrame = getActiveCallFrame(); if (callFrame != null) { debuggerApi.evaluateExpressionOnCallFrame(sessionId, callFrame, expression); } else { debuggerApi.evaluateExpression(sessionId, expression); } } } void requestAllCssStyleSheets() { if (active) { debuggerApi.requestAllCssStyleSheets(sessionId); } } void setStyleSheetText(String styleSheetId, String text) { if (active) { debuggerApi.setStyleSheetText(sessionId, styleSheetId, text); } } void setBreakpoint(Breakpoint breakpoint) { if (active && breakpoint.isActive()) { BreakpointInfoImpl breakpointInfo = findBreakpointInfo(breakpoint); if (breakpointInfo == null) { breakpointInfo = new BreakpointInfoImpl(breakpoint, sourceMapping.getRemoteBreakpoint(breakpoint)); breakpointInfos.add(breakpointInfo); } if (StringUtils.isNullOrEmpty(breakpointInfo.breakpointId)) { // Send to the debugger if it's not yet resolved. debuggerApi.setBreakpointByUrl(sessionId, breakpointInfo); } } } void removeBreakpoint(Breakpoint breakpoint) { if (active && breakpoint.isActive()) { BreakpointInfoImpl breakpointInfo = findBreakpointInfo(breakpoint); if (breakpointInfo != null && !StringUtils.isNullOrEmpty(breakpointInfo.breakpointId)) { debuggerApi.removeBreakpoint(sessionId, breakpointInfo.breakpointId); } else { Log.error(getClass(), "Breakpoint to remove not found: " + breakpoint); } } } void setBreakpointsEnabled(boolean enabled) { if (active) { debuggerApi.setBreakpointsActive(sessionId, enabled); } } void sendCustomMessage(String message) { if (active) { debuggerApi.sendCustomMessage(sessionId, message); } } @VisibleForTesting BreakpointInfoImpl findBreakpointInfo(Breakpoint breakpoint) { for (int i = 0, n = breakpointInfos.size(); i < n; ++i) { BreakpointInfoImpl breakpointInfo = breakpointInfos.get(i); if (breakpoint.equals(breakpointInfo.breakpoint)) { return breakpointInfo; } } return null; } private void setActive(boolean value) { if (active != value) { Preconditions.checkState(!value, "Reactivation of debugger is not supported"); reset(); active = value; debuggerStateListenerManager.dispatch(DEBUGGER_STATE_DISPATCHER); } } private void setOnPausedResponse(@Nullable OnPausedResponse response) { if (lastOnPausedResponse != response) { lastOnPausedResponse = response; activeCallFrameIndex = 0; debuggerStateListenerManager.dispatch(DEBUGGER_STATE_DISPATCHER); } } private void reset() { softReset(); active = false; sourceMapping = null; lastOnPausedResponse = null; activeCallFrameIndex = 0; breakpointInfos.clear(); } /** * Performs a "soft" reset to clear the data that does not survive a restart * of an active debugger session. This happens when we choose to debug another * application within an already open debugger session (and debuggee window). * * TODO: We should catch the corresponding event from the extension. * The closest seems to be onGlobalObjectChanged, but it does not work. */ private void softReset() { scriptParsedResponses = JsonCollections.createMap(); } private void updateBreakpointInfo(OnBreakpointResolvedResponse response) { for (int i = 0, n = breakpointInfos.size(); i < n; ++i) { BreakpointInfoImpl breakpointInfo = breakpointInfos.get(i); if (StringUtils.equalNonEmptyStrings(response.getBreakpointId(), breakpointInfo.breakpointId) || breakpointInfo.equalsTo(response.getBreakpointInfo())) { if (!StringUtils.isNullOrEmpty(response.getBreakpointId())) { breakpointInfo.breakpointId = response.getBreakpointId(); } else { Log.error(getClass(), "Empty breakpointId in the response!"); } breakpointInfo.locations.addAll(response.getLocations()); break; } } } private void removeBreakpointById(String breakpointId) { for (int i = 0, n = breakpointInfos.size(); i < n; ++i) { BreakpointInfoImpl breakpointInfo = breakpointInfos.get(i); if (breakpointId.equals(breakpointInfo.breakpointId)) { breakpointInfos.remove(i); break; } } } /** * Implementation of {@link BreakpointInfo} that also contains information * received from the debugger. */ @VisibleForTesting static class BreakpointInfoImpl implements BreakpointInfo { private final Breakpoint breakpoint; private final BreakpointInfo delegate; // Populated from the debugger responses. private String breakpointId; private final JsonArray<Location> locations = JsonCollections.createArray(); private BreakpointInfoImpl(Breakpoint breakpoint, BreakpointInfo delegate) { this.breakpoint = breakpoint; this.delegate = delegate; } @Override public String getUrl() { return delegate.getUrl(); } @Override public String getUrlRegex() { return delegate.getUrlRegex(); } @Override public int getLineNumber() { return delegate.getLineNumber(); } @Override public int getColumnNumber() { return delegate.getColumnNumber(); } @Override public String getCondition() { return delegate.getCondition(); } public Breakpoint getBreakpoint() { return breakpoint; } public String getBreakpointId() { return breakpointId; } public JsonArray<Location> getLocations() { return locations.copy(); } private boolean equalsTo(BreakpointInfo breakpointInfo) { return breakpointInfo != null && StringUtils.equalStringsOrEmpty(getUrl(), breakpointInfo.getUrl()) && getLineNumber() == breakpointInfo.getLineNumber() && getColumnNumber() == breakpointInfo.getColumnNumber() && StringUtils.equalStringsOrEmpty(getCondition(), breakpointInfo.getCondition()); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DomInspector.java
client/src/main/java/com/google/collide/client/code/debugging/DomInspector.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.debugging; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.ui.tooltip.Tooltip; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; import elemental.events.CustomEvent; import elemental.events.Event; import elemental.events.EventListener; import elemental.html.IFrameElement; import elemental.html.LinkElement; import elemental.html.ScriptElement; /** * Dom Inspector UI. * */ public class DomInspector extends UiComponent<DomInspector.View> { private static final String DEBUGGER_CUSTOM_MESSAGE_REQUEST = "DebuggerCustomMessageRequest"; private static final String DEBUGGER_CUSTOM_MESSAGE_RESPONSE = "DebuggerCustomMessageResponse"; public interface Css extends CssResource { String root(); String domIframe(); } interface Resources extends ClientBundle, Tooltip.Resources { @Source("DomInspector.css") Css workspaceEditorDomInspectorCss(); } /** * The view of the Dom Inspector. */ static class View extends CompositeView<ViewEvents> { private final Css css; private final IFrameElement domInspectorIframe; private final EventListener customDebuggerMessageRequestListener = new EventListener() { @Override public void handleEvent(Event evt) { Object detail = ((CustomEvent) evt).getDetail(); if (detail != null) { getDelegate().onCustomMessageRequest(detail.toString()); } } }; View(Resources resources) { css = resources.workspaceEditorDomInspectorCss(); domInspectorIframe = Elements.createIFrameElement(css.domIframe()); domInspectorIframe.setOnload(new EventListener() { @Override public void handleEvent(Event evt) { onDomInspectorIframeLoaded(); } }); CssUtils.setDisplayVisibility(domInspectorIframe, false); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(domInspectorIframe); setElement(rootElement); } private void show() { if (!isVisible()) { CssUtils.setDisplayVisibility(domInspectorIframe, true); // Ping with an empty message to re-initialize. sendCustomMessageResponseToInspector(""); } } private void hide() { CssUtils.setDisplayVisibility(domInspectorIframe, false); } private boolean isVisible() { return CssUtils.isVisible(domInspectorIframe); } private void onDomInspectorIframeLoaded() { // <link href="test.css" rel="stylesheet" type="text/css"> LinkElement linkElement = Elements.getDocument().createLinkElement(); linkElement.setRel("stylesheet"); linkElement.setType("text/css"); linkElement.setHref("/static/dominspector_css_compiled.css"); Elements.getHead(domInspectorIframe.getContentDocument()).appendChild(linkElement); ScriptElement scriptElement = Elements.getDocument().createScriptElement(); scriptElement.setSrc("/static/dominspector_js_compiled.js"); Elements.getBody(domInspectorIframe.getContentDocument()).appendChild(scriptElement); domInspectorIframe.getContentWindow().addEventListener( DEBUGGER_CUSTOM_MESSAGE_REQUEST, customDebuggerMessageRequestListener, false); } private void sendCustomMessageResponseToInspector(String response) { if (domInspectorIframe.getContentDocument() != null && domInspectorIframe.getContentWindow() != null) { CustomEvent evt = (CustomEvent) domInspectorIframe.getContentDocument().createEvent( "CustomEvent"); evt.initCustomEvent(DEBUGGER_CUSTOM_MESSAGE_RESPONSE, true, true, response); domInspectorIframe.getContentWindow().dispatchEvent(evt); } } } /** * The view events. */ private interface ViewEvents { void onCustomMessageRequest(String message); } static DomInspector create(View view, DebuggerState debuggerState) { return new DomInspector(view, debuggerState); } private final DebuggerState debuggerState; private final DebuggerState.CustomMessageListener customDebuggerMessageResponseListener = new DebuggerState.CustomMessageListener() { @Override public void onCustomMessageResponse(String response) { getView().sendCustomMessageResponseToInspector(response); } }; @VisibleForTesting DomInspector(View view, DebuggerState debuggerState) { super(view); this.debuggerState = debuggerState; debuggerState.getCustomMessageListenerRegistrar().add(customDebuggerMessageResponseListener); view.setDelegate(new ViewEvents() { @Override public void onCustomMessageRequest(String message) { DomInspector.this.debuggerState.sendCustomMessage(message); } }); } void show() { getView().show(); } void hide() { getView().hide(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/errorrenderer/ErrorReceiver.java
client/src/main/java/com/google/collide/client/code/errorrenderer/ErrorReceiver.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.errorrenderer; import com.google.collide.dto.CodeError; import com.google.collide.json.shared.JsonArray; /** * A receiver which handles notifying the editor of code errors. * */ public interface ErrorReceiver { /** * Gets notified about code errors detected in a source file. */ public static interface ErrorListener { /** * Signals that the list of errors in a file has changed. * * @param errors new list of all errors in the file */ void onErrorsChanged(JsonArray<CodeError> errors); } public void setActiveDocument(String fileEditSessionKey); public void addErrorListener(String fileEditSessionKey, ErrorListener listener); public void removeErrorListener(String fileEditSessionKey, ErrorListener listener); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/errorrenderer/ErrorRenderer.java
client/src/main/java/com/google/collide/client/code/errorrenderer/ErrorRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.errorrenderer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.client.util.logging.Log; import com.google.collide.dto.CodeError; import com.google.collide.dto.FilePosition; import com.google.collide.dto.client.DtoClientImpls; import com.google.collide.json.client.JsoArray; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineNumberAndColumn; import com.google.collide.shared.ot.PositionMigrator; import com.google.collide.shared.util.SortedList; /** * Renders code errors in the editor. */ public class ErrorRenderer implements LineRenderer { private static final SortedList.Comparator<CodeError> ERROR_COMPARATOR = new SortedList.Comparator<CodeError>() { @Override public int compare(CodeError error1, CodeError error2) { int startLineDiff = error1.getErrorStart().getLineNumber() - error2.getErrorStart().getLineNumber(); if (startLineDiff != 0) { return startLineDiff; } int startColumnDiff = error1.getErrorStart().getColumn() - error2.getErrorStart().getColumn(); if (startColumnDiff != 0) { return startColumnDiff; } int endLineDiff = error1.getErrorEnd().getLineNumber() - error2.getErrorEnd().getLineNumber(); if (endLineDiff != 0) { return endLineDiff; } else { return error1.getErrorEnd().getColumn() - error2.getErrorEnd().getColumn(); } } }; public JsonArray<CodeError> getCodeErrors() { return codeErrors; } private final Editor.Css css; private int currentLineNumber; private int currentLineLength; // Current render start position. private int linePosition; // Errors that are visible at current line. They may start on the previous line // (or even earlier) or end in one of the next lines. private SortedList<CodeError> lineErrors; // Index of next error to render in lineErrors array. private int nextErrorIndex; // List of errors for a file. private JsonArray<CodeError> codeErrors; private PositionMigrator positionMigrator; public ErrorRenderer(Editor.Resources res) { this.css = res.workspaceEditorCss(); codeErrors = JsoArray.create(); } @Override public void renderNextChunk(Target target) { CodeError nextError = getNextErrorToRender(); if (nextError == null) { // No errors to render. So render the rest of the line with null. renderNothingAndProceed(target, currentLineLength - linePosition); } else if (nextError.getErrorStart().getLineNumber() < currentLineNumber || nextError.getErrorStart().getColumn() == linePosition) { int errorLength; if (nextError.getErrorEnd().getLineNumber() > currentLineNumber) { errorLength = currentLineLength - linePosition; } else { // Error ends at current line. errorLength = nextError.getErrorEnd().getColumn() + 1 - linePosition; } renderErrorAndProceed(target, errorLength); } else { // Wait until we get to the next error. renderNothingAndProceed(target, nextError.getErrorStart().getColumn() - linePosition); } } @Override public boolean shouldLastChunkFillToRight() { return false; } private void renderErrorAndProceed(Target target, int characterCount) { Log.debug(getClass(), "Rendering " + characterCount + " characters with error style at position " + linePosition + ", next line position: " + (linePosition + characterCount)); target.render(characterCount, css.lineRendererError()); linePosition += characterCount; nextErrorIndex++; } private void renderNothingAndProceed(Target target, int characterCount) { target.render(characterCount, null); linePosition += characterCount; } private CodeError getNextErrorToRender() { while (nextErrorIndex < lineErrors.size()) { CodeError nextError = lineErrors.get(nextErrorIndex); if (nextError.getErrorEnd().getLineNumber() == currentLineNumber && nextError.getErrorEnd().getColumn() < linePosition) { // This may happen if errors overlap. nextErrorIndex++; continue; } else { return nextError; } } return null; } @Override public boolean resetToBeginningOfLine(Line line, int lineNumber) { // TODO: Convert to anchors so that error positions are updated when text edits happen. this.lineErrors = getErrorsAtLine(lineNumber); if (lineErrors.size() > 0) { Log.debug(getClass(), "Rendering line: " + lineNumber, ", errors size: " + lineErrors.size()); } else { return false; } this.currentLineNumber = lineNumber; this.currentLineLength = line.getText().length(); this.nextErrorIndex = 0; this.linePosition = 0; return true; } private SortedList<CodeError> getErrorsAtLine(int lineNumber) { int oldLineNumber = migrateLineNumber(lineNumber); SortedList<CodeError> result = new SortedList<CodeError>(ERROR_COMPARATOR); for (int i = 0; i < codeErrors.size(); i++) { CodeError error = codeErrors.get(i); if (error.getErrorStart().getLineNumber() <= oldLineNumber && error.getErrorEnd().getLineNumber() >= oldLineNumber) { result.add(migrateError(error)); } } return result; } private int migrateLineNumber(int lineNumber) { if (positionMigrator == null) { return lineNumber; } else { return positionMigrator.migrateFromNow(lineNumber, 0).lineNumber; } } private CodeError migrateError(CodeError oldError) { FilePosition newErrorStart = migrateFilePositionToNow(oldError.getErrorStart()); FilePosition newErrorEnd = migrateFilePositionToNow(oldError.getErrorEnd()); if (newErrorStart == oldError.getErrorStart() && newErrorEnd == oldError.getErrorEnd()) { return oldError; } DtoClientImpls.CodeErrorImpl newError = DtoClientImpls.CodeErrorImpl.make() .setErrorStart(newErrorStart) .setErrorEnd(newErrorEnd) .setMessage(oldError.getMessage()); Log.debug(getClass(), "Migrated error [" + codeErrorToString(oldError) + "] to [" + codeErrorToString(newError) + "]"); return newError; } private FilePosition migrateFilePositionToNow(FilePosition filePosition) { if (!positionMigrator.haveChanges()) { return filePosition; } LineNumberAndColumn newPosition = positionMigrator.migrateToNow(filePosition.getLineNumber(), filePosition.getColumn()); return DtoClientImpls.FilePositionImpl.make() .setLineNumber(newPosition.lineNumber) .setColumn(newPosition.column); } public void setCodeErrors(JsonArray<CodeError> codeErrors, PositionMigrator positionMigrator) { this.codeErrors = codeErrors; this.positionMigrator = positionMigrator; } private static String filePositionToString(FilePosition position) { return "(" + position.getLineNumber() + "," + position.getColumn() + ")"; } private static String codeErrorToString(CodeError codeError) { if (codeError == null) { return "null"; } else { return filePositionToString(codeError.getErrorStart()) + "-" + filePositionToString(codeError.getErrorEnd()); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/errorrenderer/EditorErrorListener.java
client/src/main/java/com/google/collide/client/code/errorrenderer/EditorErrorListener.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.errorrenderer; import com.google.collide.client.editor.Editor; import com.google.collide.dto.CodeError; import com.google.collide.dto.client.ClientDocOpFactory; import com.google.collide.json.client.JsoArray; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.ot.PositionMigrator; /** * Connection point of Editor and Error Receiver. * Attaches to Editor to render received errors. */ public class EditorErrorListener implements ErrorReceiver.ErrorListener { /** An error receiver which never receives any errors */ public static ErrorReceiver NOOP_ERROR_RECEIVER = new ErrorReceiver() { @Override public void setActiveDocument(String fileEditSessionKey) {} @Override public void addErrorListener(String fileEditSessionKey, ErrorListener listener) {} @Override public void removeErrorListener(String fileEditSessionKey, ErrorListener listener) {} }; private final Editor editor; private final ErrorRenderer errorRenderer; private final ErrorReceiver errorReceiver; private final PositionMigrator positionMigrator; private String currentFileEditSessionKey; public EditorErrorListener( Editor editor, ErrorReceiver errorReceiver, ErrorRenderer errorRenderer) { this.editor = editor; this.errorReceiver = errorReceiver; this.errorRenderer = errorRenderer; this.positionMigrator = new PositionMigrator(ClientDocOpFactory.INSTANCE); } @Override public void onErrorsChanged(JsonArray<CodeError> newErrors) { if (editor.getDocument() == null) { return; } JsonArray<Line> linesToRender = JsoArray.create(); getLinesOfErrorsInViewport(errorRenderer.getCodeErrors(), linesToRender); getLinesOfErrorsInViewport(newErrors, linesToRender); positionMigrator.reset(); errorRenderer.setCodeErrors(newErrors, positionMigrator); for (int i = 0; i < linesToRender.size(); i++) { editor.getRenderer().requestRenderLine(linesToRender.get(i)); } editor.getRenderer().renderChanges(); } private void getLinesOfErrorsInViewport(JsonArray<CodeError> errors, JsonArray<Line> lines) { LineFinder lineFinder = editor.getDocument().getLineFinder(); int topLineNumber = editor.getViewport().getTopLineNumber(); int bottomLineNumber = editor.getViewport().getBottomLineNumber(); for (int i = 0; i < errors.size(); i++) { CodeError error = errors.get(i); for (int j = error.getErrorStart().getLineNumber(); j <= error.getErrorEnd().getLineNumber(); j++) { if (j >= topLineNumber && j <= bottomLineNumber) { lines.add(lineFinder.findLine(j).line()); } } } } public void cleanup() { positionMigrator.stop(); errorReceiver.removeErrorListener(currentFileEditSessionKey, this); currentFileEditSessionKey = null; } public void onDocumentChanged(Document document, String fileEditSessionKey) { if (currentFileEditSessionKey != null) { // We no longer want to listen for new errors in old file. errorReceiver.removeErrorListener(currentFileEditSessionKey, this); } currentFileEditSessionKey = fileEditSessionKey; positionMigrator.start(document.getTextListenerRegistrar()); errorReceiver.addErrorListener(currentFileEditSessionKey, this); errorReceiver.setActiveDocument(currentFileEditSessionKey); errorRenderer.setCodeErrors(JsoArray.<CodeError>create(), positionMigrator); editor.addLineRenderer(errorRenderer); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/DynamicReferenceProvider.java
client/src/main/java/com/google/collide/client/code/gotodefinition/DynamicReferenceProvider.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import javax.annotation.Nullable; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeNode; import com.google.collide.client.util.PathUtil; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.LineInfo; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; /** * Strictly speaking, this class gives an answer to a question "is there a * reference at given file position?". It uses local parser with a delay to * find URL links / local file links or anchor references. * It is "dynamic" in a sense that it does not keep any state. */ public class DynamicReferenceProvider { // Word chars, digits or dash, at least one. private static final String DOMAIN_CHARS = "[\\w\\-\\d]+"; // ":" plus at least one digit, optional. private static final String PORT_CHARS = "(\\:\\d+)?"; @VisibleForTesting static final RegExp REGEXP_URL = RegExp.compile("\\b(https?|ftp)://(" + DOMAIN_CHARS + "\\.)*" + DOMAIN_CHARS + PORT_CHARS + "[^\\.\\s\\\"']*(\\.[^\\.\\s\\\"']+)*", "gi"); private final String contextPath; private final DeferringLineParser parser; private final FileTreeModel fileTreeModel; private final AnchorTagParser anchorTagParser; public DynamicReferenceProvider(String contextPath, DeferringLineParser parser, FileTreeModel fileTreeModel, @Nullable AnchorTagParser anchorTagParser) { this.contextPath = contextPath; this.parser = parser; this.fileTreeModel = fileTreeModel; this.anchorTagParser = anchorTagParser; } /** * Attemps to find a reference at given position. This method cannot find any * references if line is not yet parsed. This is always true if the method * was not called before. {@code blocking} flag tells whether we should wait * until the line is parsed and find a reference. * * @param lineInfo line to look reference at * @param column column to look reference at * @param blocking whether to block until given line is parsed * @return found reference at given position or {@code null} if line is not * yet parsed (happens only when {@code blocking} is {@code false} OR * if there's not reference at given position */ NavigableReference getReferenceAt(LineInfo lineInfo, int column, boolean blocking) { JsonArray<Token> parsedLineTokens = parser.getParseResult(lineInfo, blocking); // TODO: We should get parser state here. if (parsedLineTokens == null) { return null; } return getReferenceAt(lineInfo, column, parsedLineTokens); } @VisibleForTesting NavigableReference getReferenceAt(LineInfo lineInfo, int column, JsonArray<Token> tokens) { /* We care about: * - "href" attribute values in "a" tag, looking for anchors defined elsewhere, * - all comment and string literals, looking for urls, * - "src" or "href" attribute values, looking for urls and local file paths. */ boolean inAttribute = false; boolean inAnchorTag = false; boolean inHrefAttribute = false; int tokenEndColumn = 0; for (int i = 0, l = tokens.size() - 1; i < l; i++) { Token token = tokens.get(i); TokenType type = token.getType(); String value = token.getValue(); int tokenStartColumn = tokenEndColumn; tokenEndColumn += value.length(); // Exclusive. if (type == TokenType.TAG) { if (">".equals(value) || "/>".equals(value)) { inAttribute = false; inHrefAttribute = false; } inAnchorTag = "<a".equalsIgnoreCase(value); continue; } else if (type == TokenType.ATTRIBUTE) { if (inAnchorTag && "href".equals(value)) { inHrefAttribute = true; inAttribute = true; } else if ("src".equals(value) || "href".equals(value)) { inAttribute = true; } continue; } else if (tokenEndColumn <= column) { // Too early. continue; } else if (tokenStartColumn > column) { // We went too far, we have nothing. return null; } else if (type != TokenType.STRING && type != TokenType.COMMENT) { continue; } // So now the token covers given position and we're in a string/comment or we're in attribute // "src" or "href". Awesome! int lineNumber = lineInfo.number(); int valueStartColumn = tokenStartColumn; int valueEndColumn = tokenEndColumn; // Exclusive. String valueWithoutQuotes = value; if (inAttribute && value.startsWith("\"") && value.endsWith("\"")) { valueWithoutQuotes = value.substring(1, value.length() - 1); valueStartColumn++; valueEndColumn--; } if (valueStartColumn > column || column >= valueEndColumn) { continue; } // Now check if the value is a workspace file path. if (inAttribute) { FileTreeNode fileNode = findFileNode(valueWithoutQuotes); if (fileNode != null) { int filePathEndColumn = valueEndColumn - 1; // Incl. return NavigableReference.createToFile(lineNumber, valueStartColumn, filePathEndColumn, fileNode.getNodePath().getPathString()); } } // Now check if the value is an URL. REGEXP_URL.setLastIndex(0); for (MatchResult matchResult = REGEXP_URL.exec(valueWithoutQuotes); matchResult != null; matchResult = REGEXP_URL.exec(valueWithoutQuotes)) { int matchColumn = valueStartColumn + matchResult.getIndex(); int matchEndColumn = matchColumn + matchResult.getGroup(0).length() - 1; // Inclusive. if (matchEndColumn < column) { // Too early. continue; } if (matchColumn > column) { // Too far. return null; } return NavigableReference.createToUrl(lineNumber, matchColumn, matchResult.getGroup(0)); } // Now check if the value is the name of the anchor tag. if (inHrefAttribute && valueWithoutQuotes.startsWith("#")) { AnchorTagParser.AnchorTag anchorTag = findAnchorTag(valueWithoutQuotes.substring(1)); if (anchorTag != null) { return NavigableReference.createToFile( lineNumber, valueStartColumn, valueEndColumn - 1, contextPath, anchorTag.getLineNumber(), anchorTag.getColumn()); } } } return null; } @VisibleForTesting FileTreeNode findFileNode(String displayPath) { PathUtil lookupPath = new PathUtil(displayPath); if (!displayPath.startsWith("/")) { PathUtil contextDir = PathUtil.createExcludingLastN(new PathUtil(contextPath), 1); lookupPath = PathUtil.concatenate(contextDir, lookupPath); } return fileTreeModel.getWorkspaceRoot().findChildNode(lookupPath); } private AnchorTagParser.AnchorTag findAnchorTag(String name) { if (anchorTagParser == null) { return null; } JsonArray<AnchorTagParser.AnchorTag> anchorTags = anchorTagParser.getAnchorTags(); for (int i = 0; i < anchorTags.size(); i++) { if (anchorTags.get(i).getName().equalsIgnoreCase(name)) { return anchorTags.get(i); } } return null; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/AnchorTagParser.java
client/src/main/java/com/google/collide/client/code/gotodefinition/AnchorTagParser.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import com.google.collide.client.documentparser.AsyncParser; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.client.util.logging.Log; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.codemirror2.XmlState; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.StringUtils; /** * Extracts anchor tags with names using document parser, asynchronously. */ public class AnchorTagParser extends AsyncParser<AnchorTagParser.AnchorTag> { static class AnchorTag implements AsyncParser.LineAware { private final int lineNumber; private final int column; private final String name; AnchorTag(int lineNumber, int column, String name) { this.lineNumber = lineNumber; this.column = column; this.name = name; } @Override public int getLineNumber() { return lineNumber; } public int getColumn() { return column; } public String getName() { return name; } } private final ListenerRegistrar.Remover listenerRemover; private final DocumentParser parser; private JsonArray<AnchorTag> anchorTags; private boolean inAnchorTag = false; private boolean inNameAttribute = false; /** * Creates and registers anchor parser. */ public AnchorTagParser(DocumentParser parser) { this.parser = parser; listenerRemover = parser.getListenerRegistrar().add(this); } @Override public void onParseLine(Line line, int lineNumber, JsonArray<Token> tokens) { ParseResult<XmlState> parserState = parser.getState(XmlState.class, new Position(new LineInfo(line, lineNumber), 0), null); if (parserState != null && parserState.getState() != null && parserState.getState().getContext() != null && "a".equalsIgnoreCase(parserState.getState().getContext().getTagName())) { inAnchorTag = true; } int tokenEndColumn = 0; for (int i = 0, l = tokens.size() - 1; i < l; i++) { Token token = tokens.get(i); TokenType type = token.getType(); String value = token.getValue(); int tokenStartColumn = tokenEndColumn; tokenEndColumn += value.length(); if (type == TokenType.TAG) { if (">".equals(value) || "/>".equals(value)) { inAnchorTag = false; inNameAttribute = false; } else if ("<a".equalsIgnoreCase(value)) { inAnchorTag = true; inNameAttribute = false; } continue; } else if (inAnchorTag && type == TokenType.ATTRIBUTE && ("name".equals(value) || "id".equals(value))) { inNameAttribute = true; continue; } else if (inNameAttribute && type == TokenType.STRING) { int valueStartColumn = tokenStartColumn; if (value.startsWith("\"") && value.endsWith("\"")) { value = value.substring(1, value.length() - 1); valueStartColumn++; } if (value.length() > 0 && !StringUtils.isNullOrWhitespace(value)) { Log.debug(getClass(), "Found anchor tag with name \"" + value + "\" at (" + lineNumber + "," + valueStartColumn + ")"); addData(new AnchorTag(lineNumber, valueStartColumn, value)); } } } } @Override protected void onAfterParse(JsonArray<AnchorTag> tags) { anchorTags = tags; } public JsonArray<AnchorTag> getAnchorTags() { return anchorTags; } /** * Cleanup object. * * After cleanup is invoked this instance should never be used. */ @Override public void cleanup() { super.cleanup(); listenerRemover.remove(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/DeferringLineParser.java
client/src/main/java/com/google/collide/client/code/gotodefinition/DeferringLineParser.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import javax.annotation.Nullable; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.util.DeferredCommandExecutor; import com.google.collide.client.util.logging.Log; import com.google.collide.codemirror2.Token; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Lazily parses source lines. That is, defers parsing for some time. * 2 possible states are - line is parsed, parse results are ready, and * parsing is not finished, no results available. * */ public class DeferringLineParser { private final DocumentParser parser; private LineInfo scheduledParseLineInfo; private int parsedLineNumber = -1; private JsonArray<Token> parsedLineTokens; private final DeferredCommandExecutor parseExecutor = new DeferredCommandExecutor(25) { @Override protected boolean execute() { parseScheduledLine(); return false; } }; private void parseScheduledLine() { Preconditions.checkState(scheduledParseLineInfo != null); parsedLineTokens = parseLine(scheduledParseLineInfo); parsedLineNumber = scheduledParseLineInfo.number(); scheduledParseLineInfo = null; } private JsonArray<Token> parseLine(LineInfo lineInfo) { JsonArray<Token> tokens = parser.parseLineSync(lineInfo.line()); if (tokens == null) { tokens = JsonCollections.createArray(); } Log.debug(getClass(), "Line " + lineInfo.number() + " parsed, number of tokens: " + tokens.size()); return tokens; } /** * Creates a new deferring parser. * * @param parser document parser to use */ public DeferringLineParser(DocumentParser parser) { this.parser = parser; } /** * Returns available parse results or schedules parsing. Does not collect * parse results, i.e. at given time parse results only for a single line * are available. * * @param lineInfo line to parse * @param blocking whether to block until the line is parsed * @return parsed tokens or {@code null} if no results available now */ JsonArray<Token> getParseResult(LineInfo lineInfo, boolean blocking) { // TODO: We should get parser state here. if (parsedLineNumber == lineInfo.number()) { Preconditions.checkState(parsedLineTokens != null); return parsedLineTokens; } else if (blocking) { scheduleParse(null); // Cancel anything currently scheduled. parsedLineTokens = parseLine(lineInfo); parsedLineNumber = lineInfo.number(); return parsedLineTokens; } else { scheduleParse(lineInfo); return null; } } private void scheduleParse(@Nullable LineInfo lineInfo) { if (lineInfo == null && scheduledParseLineInfo == null) { return; } if (scheduledParseLineInfo != null && lineInfo != null && scheduledParseLineInfo.number() == lineInfo.number()) { return; } if (scheduledParseLineInfo != null) { parseExecutor.cancel(); // Cancel anything currently scheduled. } scheduledParseLineInfo = lineInfo; if (scheduledParseLineInfo == null) { return; } parseExecutor.schedule(2); Log.debug(getClass(), "Scheduled line parse for line number " + scheduledParseLineInfo.number()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/ReferenceNavigator.java
client/src/main/java/com/google/collide/client/code/gotodefinition/ReferenceNavigator.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import com.google.collide.client.code.FileSelectedPlace; import com.google.collide.client.editor.Editor; import com.google.collide.client.history.Place; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.logging.Log; import com.google.gwt.core.client.Scheduler; import elemental.client.Browser; /** * Helper class that performs navigation for various references. * */ class ReferenceNavigator { private final Editor editor; private final Place currentPlace; private String currentFilePath; public ReferenceNavigator(Place currentPlace, Editor editor) { this.currentPlace = currentPlace; this.editor = editor; } public void goToFile(String path, final int lineNumber, final int column) { if (path.equals(currentFilePath)) { // Defer over other mouse click and mouse move listeners. Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { editor.scrollTo(lineNumber, column); } }); } else { currentPlace.fireChildPlaceNavigation(FileSelectedPlace.PLACE.createNavigationEvent( new PathUtil(path), lineNumber, column, false)); } } public void goToUrl(String url) { Log.debug(getClass(), "Navigating to URL \"" + url + "\""); Browser.getWindow().open(url,url); } public void setCurrentFilePath(String path) { this.currentFilePath = path; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/NavigableReference.java
client/src/main/java/com/google/collide/client/code/gotodefinition/NavigableReference.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import com.google.collide.client.documentparser.AsyncParser; import com.google.collide.dto.CodeReference; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * A reference in a file that can be navigated somewhere. A reference always has * a range in the file and optional snippet that tells something about where it * is pointing to. * */ abstract class NavigableReference implements AsyncParser.LineAware { private final int lineNumber; private final int startColumn; private final int endColumn; private final String snippet; private NavigableReference(int lineNumber, int startColumn, int endColumn, String snippet) { Preconditions.checkArgument(endColumn >= startColumn); this.lineNumber = lineNumber; this.startColumn = startColumn; this.endColumn = endColumn; this.snippet = snippet; } public int getLineNumber() { return lineNumber; } public int getStartColumn() { return startColumn; } public int getEndColumn() { return endColumn; } public String getSnippet() { return snippet; } public static FileReference createToFile(CodeReference reference) { return new FileReference(reference.getReferenceStart().getLineNumber(), reference.getReferenceStart().getColumn(), reference.getReferenceEnd().getColumn(), reference.getTargetSnippet(), reference.getTargetFilePath(), reference.getTargetStart().getLineNumber(), reference.getTargetStart().getColumn()); } public static FileReference createToFile(int lineNumber, int startColumn, int endColumn, String path) { return new FileReference(lineNumber, startColumn, endColumn, null, path, 0, 0); } public static FileReference createToFile(int lineNumber, int startColumn, int endColumn, String path, int targetLineNumber, int targetColumn) { return new FileReference( lineNumber, startColumn, endColumn, null, path, targetLineNumber, targetColumn); } public static UrlReference createToUrl(int lineNumber, int startColumn, String url) { return new UrlReference(lineNumber, startColumn, null, url); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof NavigableReference)) { return false; } NavigableReference that = (NavigableReference) o; return this.endColumn == that.endColumn && this.lineNumber == that.lineNumber && this.startColumn == that.startColumn && (this.snippet == null ? that.snippet == null : snippet.equals(that.snippet)); } abstract void navigate(ReferenceNavigator navigator); /** * @return short target context displayed to user or {@code null} if nothing * to display as context */ abstract String getTargetName(); @VisibleForTesting static final class FileReference extends NavigableReference { private final String targetFilePath; private final int targetLineNumber; private final int targetColumn; private FileReference(int lineNumber, int startColumn, int endColumn, String snippet, String targetFilePath, int targetLineNumber, int targetColumn) { super(lineNumber, startColumn, endColumn, snippet); this.targetFilePath = targetFilePath; this.targetLineNumber = targetLineNumber; this.targetColumn = targetColumn; } @Override void navigate(ReferenceNavigator navigator) { navigator.goToFile(targetFilePath, targetLineNumber, targetColumn); } @Override String getTargetName() { return targetFilePath; } public String getTargetFilePath() { return targetFilePath; } public String toString() { return "(" + getLineNumber() + "," + getStartColumn() + "-" + getEndColumn() + ") to file \"" + targetFilePath + "\", target position: (" + targetLineNumber + ", " + targetColumn + "\""; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FileReference) || !super.equals(o)) { return false; } FileReference that = (FileReference) o; return this.targetColumn == that.targetColumn && this.targetLineNumber == that.targetLineNumber && (this.targetFilePath == null ? that.targetFilePath == null : this.targetFilePath.equals(that.targetFilePath)); } } @VisibleForTesting static final class UrlReference extends NavigableReference { private final String url; private UrlReference(int lineNumber, int startColumn, String snippet, String url) { super(lineNumber, startColumn, startColumn + url.length() - 1, snippet); this.url = url; } @Override void navigate(ReferenceNavigator navigator) { navigator.goToUrl(url); } @Override String getTargetName() { return null; } public String getUrl() { return url; } public String toString() { return "(" + getLineNumber() + "," + getStartColumn() + "-" + getEndColumn() + ") to URL \"" + url + "\""; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof UrlReference) || !super.equals(o)) { return false; } UrlReference that = (UrlReference) o; return this.url == null ? that.url == null : this.url.equals(that.url); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/GoToDefinitionHandler.java
client/src/main/java/com/google/collide/client/code/gotodefinition/GoToDefinitionHandler.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import org.waveprotocol.wave.client.common.util.SignalEvent; import org.waveprotocol.wave.client.common.util.SignalEvent.KeyModifier; import org.waveprotocol.wave.client.common.util.UserAgent; import collide.client.filetree.FileTreeModel; import com.google.collide.client.code.popup.EditorPopupController; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.input.CommonActions; import com.google.collide.client.editor.input.DefaultActionExecutor; import com.google.collide.client.editor.input.InputScheme; import com.google.collide.client.editor.input.RootActionExecutor; import com.google.collide.client.editor.input.Shortcut; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.history.Place; import com.google.collide.client.util.PathUtil; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.StringUtils; import com.google.common.base.Preconditions; import com.google.gwt.event.dom.client.KeyCodes; import elemental.events.Event; /** * Implementation of the "go to definition" feature. * */ public class GoToDefinitionHandler extends DefaultActionExecutor { private static final int COMMAND_KEY_CODE = 91; private final Editor editor; private final FileTreeModel fileTreeModel; private final GoToDefinitionRenderer referenceRenderer; private final Shortcut gotoDefinitionAction = new Shortcut() { @Override public boolean event(InputScheme scheme, SignalEvent event) { goToDefinitionAtCurrentCaretPosition(); return true; } }; private LineFinder lineFinder; /** * Flag which specifies that object is "activated". * * <p>Activated object plugs renderer and listens to mouse to highlight * hovered items. */ private boolean activated; private ListenerRegistrar.Remover mouseMoveListenerRemover; private ListenerRegistrar.Remover mouseClickListenerRemover; private ListenerRegistrar.Remover nativeKeyUpListenerRemover; /** * Flag which specifies that object is "attached" to editor. * * <p>Registered object listens for keypeseesd (to become activated) and * provides actions. */ private boolean registered; private ListenerRegistrar.Remover keyListenerRemover; private RootActionExecutor.Remover actionRemover; private ReferenceStore referenceStore; private ReferenceNavigator referenceNavigator; private AnchorTagParser anchorParser; private static boolean isActionOnlyKey(SignalEvent signal) { // When modifier key is pressed on Mac it is instantly applied to modifiers. // So we check on Mac that only "CMD" is pressed. // On non-Mac when "CTRL" is the first key in sequence, there are no // modifiers applied yet. KeyModifier modifier = UserAgent.isMac() ? KeyModifier.META : KeyModifier.NONE; return modifier.check(signal) && (signal.getKeyCode() == getActionKeyCode()); } private static int getActionKeyCode() { return UserAgent.isMac() ? COMMAND_KEY_CODE : KeyCodes.KEY_CTRL; } private final Buffer.MouseMoveListener mouseMoveListener = new Buffer.MouseMoveListener() { @Override public void onMouseMove(int x, int y) { NavigableReference reference = findReferenceAtMousePosition(x, y, false); referenceRenderer.highlightReference(reference, editor.getRenderer(), lineFinder); } }; private final Buffer.MouseClickListener mouseClickListener = new Buffer.MouseClickListener() { @Override public void onMouseClick(int x, int y) { NavigableReference reference = findReferenceAtMousePosition(x, y, true); if (reference != null) { navigateReference(reference); } } }; private final Editor.NativeKeyUpListener keyUpListener = new Editor.NativeKeyUpListener() { @Override public boolean onNativeKeyUp(Event event) { com.google.gwt.user.client.Event gwtEvent = (com.google.gwt.user.client.Event) event; if (gwtEvent.getKeyCode() == getActionKeyCode()) { setActivated(false); return true; } else { return false; } } }; private final Editor.KeyListener keyListener = new Editor.KeyListener() { @Override public boolean onKeyPress(SignalEvent signal) { boolean shouldActivate = isActionOnlyKey(signal); setActivated(shouldActivate); return shouldActivate; } }; public GoToDefinitionHandler(Place currentPlace, Editor editor, FileTreeModel fileTreeModel, GoToDefinitionRenderer.Resources resources, CubeClient cubeClient, EditorPopupController popupController) { Preconditions.checkNotNull(editor); Preconditions.checkNotNull(cubeClient); this.editor = editor; this.fileTreeModel = fileTreeModel; this.referenceRenderer = new GoToDefinitionRenderer(resources, editor, popupController); this.referenceNavigator = new ReferenceNavigator(currentPlace, editor); addAction(CommonActions.GOTO_DEFINITION, gotoDefinitionAction); addAction(CommonActions.GOTO_SOURCE, gotoDefinitionAction); referenceStore = new ReferenceStore(cubeClient); } public void editorContentsReplaced(PathUtil filePath, DocumentParser parser) { setActivated(false); if (anchorParser != null) { anchorParser.cleanup(); anchorParser = null; } DynamicReferenceProvider dynamicReferenceProvider = null; if (isGoToDefinitionSupported(filePath)) { if (StringUtils.endsWithIgnoreCase(filePath.getPathString(), ".html")) { anchorParser = new AnchorTagParser(parser); } DeferringLineParser deferringParser = new DeferringLineParser(parser); dynamicReferenceProvider = new DynamicReferenceProvider( filePath.getPathString(), deferringParser, fileTreeModel, anchorParser); this.referenceNavigator.setCurrentFilePath(filePath.getPathString()); this.lineFinder = editor.getDocument().getLineFinder(); setRegistered(true); } else { setRegistered(false); } this.referenceStore.onDocumentChanged(editor.getDocument(), dynamicReferenceProvider); } /** * Registers or unregisters keyListener, actions, etc. */ private void setRegistered(boolean registered) { if (registered == this.registered) { return; } if (registered) { keyListenerRemover = editor.getKeyListenerRegistrar().add(keyListener); actionRemover = editor.getInput().getActionExecutor().addDelegate(this); } else { keyListenerRemover.remove(); keyListenerRemover = null; actionRemover.remove(); actionRemover = null; } this.registered = registered; } private void setActivated(boolean activated) { if (activated == this.activated) { return; } if (activated) { mouseMoveListenerRemover = editor.getBuffer().getMouseMoveListenerRegistrar().add(mouseMoveListener); mouseClickListenerRemover = editor.getBuffer().getMouseClickListenerRegistrar().add(mouseClickListener); nativeKeyUpListenerRemover = editor.getNativeKeyUpListenerRegistrar().add(keyUpListener); editor.addLineRenderer(referenceRenderer); } else { mouseMoveListenerRemover.remove(); mouseMoveListenerRemover = null; mouseClickListenerRemover.remove(); mouseClickListenerRemover = null; nativeKeyUpListenerRemover.remove(); nativeKeyUpListenerRemover = null; referenceRenderer.resetReferences(editor.getRenderer(), lineFinder); editor.removeLineRenderer(referenceRenderer); } this.activated = activated; } private static boolean isGoToDefinitionSupported(PathUtil filePath) { String pathString = filePath.getPathString(); return StringUtils.endsWithIgnoreCase(pathString, ".js") || StringUtils.endsWithIgnoreCase(pathString, ".html") || StringUtils.endsWithIgnoreCase(pathString, ".py"); } private void goToDefinitionAtCurrentCaretPosition() { // TODO: Check here that our code model is fresh enough. // int caretOffset = getCaretOffset(editor.getWidget().getElement()); SelectionModel selection = editor.getSelection(); LineInfo lineInfo = new LineInfo(selection.getCursorLine(), selection.getCursorLineNumber()); NavigableReference reference = referenceStore.findReference(lineInfo, selection.getCursorColumn(), true); navigateReference(reference); } private void navigateReference(NavigableReference reference) { if (reference == null) { return; } setActivated(false); reference.navigate(referenceNavigator); } private NavigableReference findReferenceAtMousePosition(int x, int y, boolean blocking) { int lineNumber = editor.getBuffer().convertYToLineNumber(y, true); LineInfo lineInfo = lineFinder.findLine(lineNumber); int column = editor.getBuffer().convertXToRoundedVisibleColumn(x, lineInfo.line()); return referenceStore.findReference(lineInfo, column, blocking); } public void cleanup() { referenceStore.cleanup(); if (anchorParser != null) { anchorParser.cleanup(); } setActivated(false); setRegistered(false); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/ReferenceStore.java
client/src/main/java/com/google/collide/client/code/gotodefinition/ReferenceStore.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import javax.annotation.Nullable; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.client.codeunderstanding.CubeData; import com.google.collide.client.codeunderstanding.CubeDataUpdates; import com.google.collide.client.codeunderstanding.CubeUpdateListener; import com.google.collide.client.util.logging.Log; import com.google.collide.dto.CodeReference; import com.google.collide.dto.CodeReferences; import com.google.collide.dto.FilePosition; import com.google.collide.dto.client.ClientDocOpFactory; import com.google.collide.dto.client.DtoClientImpls; import com.google.collide.json.client.Jso; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.LineNumberAndColumn; import com.google.collide.shared.ot.PositionMigrator; import com.google.common.annotations.VisibleForTesting; /** * Storage and lookup system for cubeReferences from source ranges to * another file or URLs. Collects cubeReferences from various sources like Cube * or dynamic reference provider. * */ class ReferenceStore { // Tracks docops since last time we received information from Cube. // These docops are used when we need to find reference at given position // if the position has changed as the result of user edits. private final PositionMigrator positionMigrator; private final CubeClient cubeClient; private final CubeUpdateListener cubeListener = new CubeUpdateListener() { @Override public void onCubeResponse(CubeData data, CubeDataUpdates updates) { if (!updates.isFileReferences()) { return; } updateReferences(data); } }; // References that come from Cube. private CodeReferences cubeReferences; // References that come from client parser. private DynamicReferenceProvider dynamicReferenceProvider; public ReferenceStore(CubeClient cubeClient) { this.cubeClient = cubeClient; this.positionMigrator = new PositionMigrator(ClientDocOpFactory.INSTANCE); cubeClient.addListener(cubeListener); } /** * Finds reference at given position. * * @param lineInfo position line info * @param column position column * @param blocking whether to block until given line is parsed for references * @return reference found at given position, or {@code null} if nothing there */ @VisibleForTesting NavigableReference findReference(LineInfo lineInfo, int column, boolean blocking) { // TODO: Optimize this search. // Seach for reference at position where the cursor would have been if there were // no text changes. int line = lineInfo.number(); NavigableReference result = null; if (cubeReferences != null && cubeReferences.getReferences().size() > 0) { // TODO: Optimize this search. // Seach for reference at position where the cursor would have been if there were // no text changes. LineNumberAndColumn oldPosition = positionMigrator.migrateFromNow(line, column); for (int i = 0; i < cubeReferences.getReferences().size(); i++) { CodeReference reference = cubeReferences.getReferences().get(i); if (reference.getReferenceStart().getLineNumber() > oldPosition.lineNumber) { // We've gone too far, nothing to look further. break; } if (isFilePositionBefore(reference.getReferenceStart(), oldPosition.lineNumber, oldPosition.column) && isFilePositionAfter(reference.getReferenceEnd(), oldPosition.lineNumber, oldPosition.column)) { // Migrate old reference to new position after edits. CodeReference newReference = migrateCubeReference(reference); if (newReference != null) { result = NavigableReference.createToFile(newReference); } break; } } } if (result == null && dynamicReferenceProvider != null) { result = dynamicReferenceProvider.getReferenceAt(lineInfo, column, blocking); } if (result == null) { Log.debug(getClass(), "Found no references at: (" + line + "," + column + ")"); } else { Log.debug(getClass(), "Found reference at (" + line + "," + column + "):" + result.toString()); } return result; } /** * Migrates old reference (its position as it was when we received cube data * before any edits) to new reference (new position after edits) if possible. * Reference cannot be migrated if some characters disappeared inside it or * newline was inserted in the middle. * * @param reference reference to migrate * @return migrated reference or {@code null} if reference cannot be migrated */ private CodeReference migrateCubeReference(CodeReference reference) { FilePosition oldStartPosition = reference.getReferenceStart(); FilePosition oldEndPosition = reference.getReferenceEnd(); LineNumberAndColumn newStartPosition = positionMigrator.migrateToNow( oldStartPosition.getLineNumber(), oldStartPosition.getColumn()); LineNumberAndColumn newEndPosition = positionMigrator.migrateToNow( oldEndPosition.getLineNumber(), oldEndPosition.getColumn()); int newLength = newEndPosition.column - newStartPosition.column; int oldLength = oldEndPosition.getColumn() - oldStartPosition.getColumn(); if (newStartPosition.lineNumber != newEndPosition.lineNumber || newLength != oldLength || newLength < 0) { // TODO: Make the method return null if text has changed inside the reference. return null; } DtoClientImpls.CodeReferenceImpl newReference = Jso.create().cast(); return newReference .setReferenceType(reference.getReferenceType()) .setReferenceStart(toDtoPosition(newStartPosition)) .setReferenceEnd(toDtoPosition(newEndPosition)) // TODO: Target may be in this file, in this case update target too. .setTargetStart(reference.getTargetStart()) .setTargetEnd(reference.getTargetEnd()) .setTargetFilePath(reference.getTargetFilePath()) .setTargetSnippet(reference.getTargetSnippet()); } private static FilePosition toDtoPosition(LineNumberAndColumn position) { return DtoClientImpls.FilePositionImpl.make() .setLineNumber(position.lineNumber) .setColumn(position.column); } private static boolean isFilePositionBefore(FilePosition position, int line, int column) { return position.getLineNumber() < line || (position.getLineNumber() == line && position.getColumn() <= column); } private static boolean isFilePositionAfter(FilePosition position, int line, int column) { return position.getLineNumber() > line || (position.getLineNumber() == line && position.getColumn() >= column); } private void logAllReferences() { if (cubeReferences == null) { Log.debug(getClass(), "No references info yet."); return; } Log.debug(getClass(), "All references in current file:"); for (int i = 0; i < cubeReferences.getReferences().size(); i++) { CodeReference reference = cubeReferences.getReferences().get(i); Log.debug(getClass(), "reference at: " + referenceToString(reference)); } } private static String filePositionToString(FilePosition position) { return "(" + position.getLineNumber() + "," + position.getColumn() + ")"; } private static String referenceToString(CodeReference reference) { return filePositionToString(reference.getReferenceStart()) + " to file \"" + reference.getTargetFilePath() + "\", target start: " + filePositionToString(reference.getTargetStart()) + ", target end: " + filePositionToString(reference.getTargetEnd()); } public void onDocumentChanged(Document document, @Nullable DynamicReferenceProvider dynamicReferenceProvider) { updateReferences(cubeClient.getData()); this.positionMigrator.start(document.getTextListenerRegistrar()); this.dynamicReferenceProvider = dynamicReferenceProvider; } @VisibleForTesting void updateReferences(CubeData data) { positionMigrator.reset(); this.cubeReferences = data.getFileReferences(); // referenceRenderer.resetReferences(editor.getRenderer(), lineFinder); if (Log.isLoggingEnabled()) { Log.debug(getClass(), "Received code references"); logAllReferences(); } } public void cleanup() { cubeClient.removeListener(cubeListener); positionMigrator.stop(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/gotodefinition/GoToDefinitionRenderer.java
client/src/main/java/com/google/collide/client/code/gotodefinition/GoToDefinitionRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.gotodefinition; import javax.annotation.Nullable; import collide.client.util.Elements; import com.google.collide.client.code.popup.EditorPopupController; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.ui.menu.PositionController.VerticalAlign; import com.google.collide.json.client.JsoArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.StringUtils; import com.google.common.base.Objects; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; /** * A line renderer that highlights code references "on demand". * It always highlights only one reference at a time. * */ public class GoToDefinitionRenderer implements LineRenderer { private static final int POPUP_DELAY_MS = 500; /** * CssResource for the editor. */ public interface Css extends CssResource { String referenceLink(); String referencePopup(); } /** * ClientBundle for the editor. */ public interface Resources extends ClientBundle { @Source({"GoToDefinitionRenderer.css"}) Css goToDefinitionCss(); } private class SnippetPopupRenderer implements EditorPopupController.PopupRenderer { private final Element root = Elements.createDivElement(); private final Element textContainer = (Element) root.appendChild(Elements.createPreElement( resources.goToDefinitionCss().referencePopup())); private String content; @Override public Element renderDom() { textContainer.setTextContent(content); return root; } public void setContent(String content) { this.content = content; } } private final Resources resources; private final Editor editor; private final EditorPopupController popupController; private final SnippetPopupRenderer snippetPopupRenderer; private EditorPopupController.Remover popupRemover; private int currentLineNumber; private int currentLineLength; // Current render position on current line. private int linePosition; // Reference that should be highlighted on next render. private NavigableReference highlightedReference; // Whether we have rendered the highlighted reference on current line. private boolean renderedHighlightedReference; public GoToDefinitionRenderer(Resources res, Editor editor, EditorPopupController popupController) { this.resources = res; this.editor = editor; this.popupController = popupController; snippetPopupRenderer = new SnippetPopupRenderer(); } @Override public void renderNextChunk(LineRenderer.Target target) { if (highlightedReference == null || renderedHighlightedReference) { // No references to render. So render the rest of the line with null. renderNothingAndProceed(target, currentLineLength - linePosition); } else if (highlightedReference.getLineNumber() == currentLineNumber && highlightedReference.getStartColumn() == linePosition) { // Reference starts at current line and current line position. int referenceLength; // Reference ends at current line. referenceLength = highlightedReference.getEndColumn() + 1 - linePosition; renderReferenceAndProceed(target, referenceLength); } else { // Wait until we get to the highlighted reference. renderNothingAndProceed(target, highlightedReference.getStartColumn() - linePosition); } } private void renderReferenceAndProceed(LineRenderer.Target target, int characterCount) { target.render(characterCount, resources.goToDefinitionCss().referenceLink()); renderedHighlightedReference = true; linePosition += characterCount; } private void renderNothingAndProceed(LineRenderer.Target target, int characterCount) { target.render(characterCount, null); linePosition += characterCount; } @Override public boolean resetToBeginningOfLine(Line line, int lineNumber) { if (highlightedReference == null || highlightedReference.getLineNumber() > lineNumber || highlightedReference.getLineNumber() < lineNumber) { return false; } this.renderedHighlightedReference = false; this.currentLineNumber = lineNumber; this.currentLineLength = line.getText().length(); this.linePosition = 0; return true; } @Override public boolean shouldLastChunkFillToRight() { return false; } /** * Highlights given reference. This automatically turns off highlighting * of the previously highlighed reference. * {@code renderChanges()} must be called to make the changes effective in UI. * * @param reference reference to highlight */ public void highlightReference(@Nullable NavigableReference reference, Renderer renderer, LineFinder lineFinder) { if (Objects.equal(highlightedReference, reference)) { return; } // Request clear of currently highlighted reference. if (highlightedReference != null) { requestRenderReference(highlightedReference, renderer, lineFinder); } highlightedReference = reference; if (reference != null) { requestRenderReference(reference, renderer, lineFinder); } else { removeTooltip(); } } /** * Un-highlights currently highlighted reference. */ public void resetReferences(Renderer renderer, LineFinder lineFinder) { highlightReference(null, renderer, lineFinder); } private void requestRenderReference(NavigableReference reference, Renderer renderer, LineFinder lineFinder) { renderer.requestRenderLine(lineFinder.findLine(reference.getLineNumber()).line()); createTooltipForReference(reference); } private void createTooltipForReference(NavigableReference reference) { removeTooltip(); if (reference.getSnippet() == null && reference.getTargetName() == null) { return; } // TODO: Fix scroller appearing in front of cursor if snippet is too long. String tooltipContent = JsoArray.from( StringUtils.ensureNotEmpty(reference.getTargetName(), ""), StringUtils.ensureNotEmpty(reference.getSnippet(), "")).join("\n"); snippetPopupRenderer.setContent(tooltipContent); LineInfo lineInfo = editor.getDocument().getLineFinder().findLine(reference.getLineNumber()); popupRemover = popupController.showPopup(lineInfo, reference.getStartColumn(), reference.getEndColumn(), null, snippetPopupRenderer, null, VerticalAlign.TOP, false /* shouldCaptureOutsideClickOnClose */, POPUP_DELAY_MS); } private void removeTooltip() { if (popupRemover != null) { popupRemover.remove(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/RunButtonTargetPopup.java
client/src/main/java/com/google/collide/client/workspace/RunButtonTargetPopup.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import xapi.log.X_Log; import collide.client.common.CommonResources; import collide.client.util.Elements; import com.google.collide.client.AppContext; import com.google.collide.client.plugin.RunConfiguration; import com.google.collide.client.search.FileNameSearch; import com.google.collide.client.ui.dropdown.AutocompleteController; import com.google.collide.client.ui.dropdown.AutocompleteController.AutocompleteHandler; import com.google.collide.client.ui.dropdown.DropdownController; import com.google.collide.client.ui.dropdown.DropdownController.BaseListener; import com.google.collide.client.ui.dropdown.DropdownController.DropdownPositionerBuilder; import com.google.collide.client.ui.dropdown.DropdownWidgets; import com.google.collide.client.ui.dropdown.DropdownWidgets.DropdownInput; import com.google.collide.client.ui.list.SimpleList.ListItemRenderer; import com.google.collide.client.ui.menu.AutoHideComponent; import com.google.collide.client.ui.menu.AutoHideComponent.AutoHideModel; import com.google.collide.client.ui.menu.AutoHideView; import com.google.collide.client.ui.menu.PositionController; import com.google.collide.client.ui.menu.PositionController.HorizontalAlign; import com.google.collide.client.ui.menu.PositionController.Positioner; import com.google.collide.client.ui.menu.PositionController.VerticalAlign; import com.google.collide.client.util.ClientStringUtils; import com.google.collide.client.util.PathUtil; import com.google.collide.dto.RunTarget; import com.google.collide.dto.client.DtoClientImpls.RunTargetImpl; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.RegExpUtils; import com.google.collide.shared.util.StringUtils; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.InputElement; import com.google.gwt.dom.client.LabelElement; import com.google.gwt.dom.client.SpanElement; import com.google.gwt.regexp.shared.RegExp; 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.DOM; import elemental.dom.Node; import elemental.events.Event; import elemental.events.EventListener; import elemental.events.KeyboardEvent; import elemental.util.ArrayOfString; import elemental.util.Collections; import elemental.util.MapFromStringTo; //import com.google.gwt.user.client.ui.HTMLPanel; /** * A popup for user selection of the run target. */ public class RunButtonTargetPopup extends AutoHideComponent<RunButtonTargetPopup.View, AutoHideModel> { public static RunButtonTargetPopup create(AppContext context, Element anchorElement, Element triggerElement, FileNameSearch searchIndex, MapFromStringTo<RunConfiguration> runConfigs) { MapFromStringTo<elemental.html.InputElement> inputs = Collections.mapFromStringTo(); View view = new View(context.getResources(), runConfigs, inputs); return new RunButtonTargetPopup(view, anchorElement, triggerElement, searchIndex,runConfigs,inputs); } /** * An enum which handles the different types of files that can be parsed out of a user's file * input. Each enum value also provides the appropriate labels and formatter for the user provided * values. */ public enum RunTargetType { /** * Represents any other value typed into the dropdown. This file will be executed on the * resource serving servlet. */ FILE("Query", "?query string (optional)", new InputFormatter() { @Override public String formatUserInput(String file, String userValue) { if (userValue.isEmpty()) { return StringUtils.ensureStartsWith(file, "/"); } else { return StringUtils.ensureStartsWith(file, "/") + StringUtils.ensureStartsWith(userValue, "?"); } } }); /** * An object which formats some output based on the file name and query value provided by the * user. */ public interface InputFormatter { String formatUserInput(String file, String userValue); } /** * An object which can be used for run targets which do not need to provide a formatted output. */ public static final class NoInputFormatter implements InputFormatter { @Override public String formatUserInput(String file, String userValue) { return ""; } } private final String label; private final String placeHolder; private final InputFormatter inputFormatter; RunTargetType(String label, String placeHolder, InputFormatter inputFormatter) { this.label = label; this.placeHolder = placeHolder; this.inputFormatter = inputFormatter; } /** * Parses the user's input and determines the type of run target. */ public static RunTargetType parseTargetType(String fileInput) { //check for registered plugin handlers return RunTargetType.FILE; } } public interface Css extends CssResource { String container(); String radio(); String stackedContainer(); String smallPreviewText(); String alwaysRunRow(); String alwaysRunInput(); String alwaysRunLabel(); String alwaysRunUrl(); String appUrlLabel(); String autocompleteFolder(); String listItem(); /* Sets the dropdown opacity to 1 while the menu is visible */ String stayActive(); } public interface Resources extends CommonResources.BaseResources, DropdownWidgets.Resources { @Source("RunButtonTargetPopup.css") Css runButtonTargetPopupCss(); @Source("appengine-small.png") ImageResource appengineSmall(); } public interface ViewEvents { void onAlwaysRunInputChanged(); void onPathInputChanged(); void onItemChanged(RunConfiguration runConfig); } public class ViewEventsImpl implements ViewEvents { @Override public void onAlwaysRunInputChanged() { selectRadio("ALWAYS_RUN"); getView().setDisplayForRunningApp(); } @Override public void onPathInputChanged() { selectRadio("ALWAYS_RUN"); getView().setDisplayForRunningApp(); } @Override public void onItemChanged(RunConfiguration config) { selectRadio(config.getId()); getView().setDisplayForRunningApp(); } } private static final int MAX_AUTOCOMPLETE_RESULTS = 4; private final FileNameSearch searchIndex; private final PositionController positionController; private AutocompleteController<PathUtil> autocompleteController; private final MapFromStringTo<RunConfiguration> plugins; private final MapFromStringTo<elemental.html.InputElement> inputs; private RunButtonTargetPopup( View view, Element anchorElement, Element triggerElement, FileNameSearch searchIndex, MapFromStringTo<RunConfiguration> runConfigs, MapFromStringTo<elemental.html.InputElement> inputs) { super(view, new AutoHideModel()); view.setDelegate(new ViewEventsImpl()); this.searchIndex = searchIndex; this.plugins = runConfigs; this.inputs = inputs; setupAutocomplete(); // Don't eat outside clicks and only hide when the user clicks away addPartnerClickTargets( Elements.asJsElement(triggerElement), autocompleteController.getDropdown().getElement()); setCaptureOutsideClickOnClose(false); setDelay(-1); // Position Controller positionController = new PositionController(new PositionController.PositionerBuilder().setVerticalAlign( VerticalAlign.BOTTOM).setHorizontalAlign(HorizontalAlign.LEFT) .buildAnchorPositioner(Elements.asJsElement(anchorElement)), getView().getElement()); } private void setupAutocomplete() { AutocompleteHandler<PathUtil> handler = new AutocompleteHandler<PathUtil>() { @Override public JsonArray<PathUtil> doCompleteQuery(String query) { PathUtil searchPath = PathUtil.WORKSPACE_ROOT; // the PathUtil.createExcluding wasn't used here since it doesn't make // /test2/ into a path containing /test2 but instead makes it / if (query.lastIndexOf(PathUtil.SEP) != -1) { searchPath = new PathUtil(query.substring(0, query.lastIndexOf(PathUtil.SEP))); query = query.substring(query.lastIndexOf(PathUtil.SEP) + 1); } // Only the non folder part (if it exists) is supported for wildcards RegExp reQuery = RegExpUtils.createRegExpForWildcardPattern( query, ClientStringUtils.containsUppercase(query) ? "" : "i"); return searchIndex.getMatchesRelativeToPath(searchPath, reQuery, MAX_AUTOCOMPLETE_RESULTS); } @Override public void onItemSelected(PathUtil item) { getView().runAlwaysDropdown.getInput().setValue(item.getPathString()); getView().setDisplayForRunningApp(); } }; BaseListener<PathUtil> clickListener = new BaseListener<PathUtil>() { @Override public void onItemClicked(PathUtil item) { getView().runAlwaysDropdown.getInput().setValue(item.getPathString()); getView().setDisplayForRunningApp(); //TODO(james) switch to gwt/ant/maven if the current file is of the correct format //.gwt.xml, build.xml or pom.xml } }; ListItemRenderer<PathUtil> itemRenderer = new ListItemRenderer<PathUtil>() { @Override public void render(elemental.dom.Element listItemBase, PathUtil itemData) { elemental.html.SpanElement fileNameElement = Elements.createSpanElement(); elemental.html.SpanElement folderNameElement = Elements.createSpanElement( getView().res.runButtonTargetPopupCss().autocompleteFolder()); listItemBase.appendChild(fileNameElement); listItemBase.appendChild(folderNameElement); int size = itemData.getPathComponentsCount(); if (size == 1) { fileNameElement.setTextContent(itemData.getPathComponent(0)); folderNameElement.setTextContent(""); } else { fileNameElement.setTextContent(itemData.getPathComponent(size - 1)); folderNameElement.setTextContent(" - " + itemData.getPathComponent(size - 2)); } } }; Positioner positioner = new DropdownPositionerBuilder().buildAnchorPositioner( getView().runAlwaysDropdown.getInput()); DropdownController<PathUtil> autocompleteDropdown = new DropdownController.Builder<PathUtil>( positioner, null, getView().res, clickListener, itemRenderer).setInputTargetElement( getView().runAlwaysDropdown.getInput()) .setShouldAutoFocusOnOpen(false).setKeyboardSelectionEnabled(true).build(); autocompleteController = AutocompleteController.create( getView().runAlwaysDropdown.getInput(), autocompleteDropdown, handler); } public void updateCurrentFile(String filePath) { getView().runPreviewCurrentFile.setInnerText( StringUtils.ensureNotEmpty(filePath, "Select a file")); } private void selectRadio(String mode) { elemental.html.InputElement preview = Elements.asJsElement(getView().runPreviewRadio); elemental.html.InputElement always = Elements.asJsElement(getView().runAlwaysRadio); X_Log.info("Selected",mode); preview.setChecked("PREVIEW_CURRENT_FILE".equals(mode)); always.setChecked("ALWAYS_RUN".equals(mode)); ArrayOfString keys = plugins.keys(); for (int i = 0; i < keys.length(); i++) { String key = keys.get(i); elemental.html.InputElement input = inputs.get(key); if (input != null) input.setChecked(plugins.get(key).getId().equals(mode)); } } public void setRunTarget(RunTarget runTarget) { selectRadio(runTarget.getRunMode()); getView().runAlwaysDropdown.getInput().setValue(StringUtils.nullToEmpty( runTarget.getAlwaysRunFilename())); getView().userExtraInput.setValue(StringUtils.nullToEmpty(runTarget.getAlwaysRunUrlOrQuery())); //XXX this is where we set previous gwt/ant/maven run Strings } public RunTarget getRunTarget() { RunTargetImpl runTarget = RunTargetImpl.make(); runTarget.setRunMode( isChecked(getView().runPreviewRadio)? "PREVIEW_CURRENT_FILE" : isChecked(getView().runAlwaysRadio) ? "ALWAYS_RUN" : getChecked()); runTarget.setAlwaysRunFilename(getView().runAlwaysDropdown.getInput().getValue()); runTarget.setAlwaysRunUrlOrQuery(getView().userExtraInput.getValue()); return runTarget; } private String getChecked() { ArrayOfString keys = inputs.keys(); for (int i = 0; i < keys.length(); i++) { String key = keys.get(i); if (inputs.get(key).isChecked()) { return key; } } return "ALWAYS_RUN"; } private boolean isChecked(InputElement input){ return Elements.<InputElement, elemental.html.InputElement>asJsElement(input).isChecked(); } @Override public void show() { // Position Ourselves positionController.updateElementPosition(); // Update UI before we show getView().setDisplayForRunningApp(); super.show(); } public static class View extends AutoHideView<ViewEvents> { @UiTemplate("RunButtonTargetPopup.ui.xml") interface RunButtonDropdownUiBinder extends UiBinder<Element, View> { } private static RunButtonDropdownUiBinder uiBinder = GWT.create(RunButtonDropdownUiBinder.class); @UiField(provided = true) final Resources res; // Preview Current File Stuff @UiField InputElement runPreviewRadio; @UiField LabelElement runPreviewLabel; @UiField SpanElement runPreviewCurrentFile; //Run gwt stuff // @UiField // InputElement runGwtRadio; // // @UiField // LabelElement runGwtLabel; // // @UiField // DivElement runGwtRow; // Full Query URL @UiField DivElement container; // Run always stuff @UiField DivElement runAlwaysRow; @UiField InputElement runAlwaysRadio; @UiField LabelElement runAlwaysLabel; final DropdownInput runAlwaysDropdown; // Query and URL Box @UiField LabelElement userExtraLabel; @UiField InputElement userExtraInput; // Full Query URL @UiField DivElement runHintText; public View(Resources resources, MapFromStringTo<RunConfiguration> runConfigs, MapFromStringTo<elemental.html.InputElement> inputs) { this.res = resources; Element element = uiBinder.createAndBindUi(this); setElement(Elements.asJsElement(element)); Elements.getBody().appendChild((Node) element); // Workaround for inability to set both id and ui:field in a UiBinder XML runAlwaysRadio.setId(DOM.createUniqueId()); runAlwaysLabel.setHtmlFor(runAlwaysRadio.getId()); userExtraLabel.setHtmlFor(runAlwaysRadio.getId()); runPreviewRadio.setId(DOM.createUniqueId()); runPreviewLabel.setHtmlFor(runPreviewRadio.getId()); // Create the dropdown runAlwaysDropdown = new DropdownInput(resources); runAlwaysDropdown.getInput() .addClassName(resources.runButtonTargetPopupCss().alwaysRunInput()); runAlwaysDropdown.getInput().setAttribute("placeholder", "Enter filename"); Elements.asJsElement(runAlwaysRow).appendChild(runAlwaysDropdown.getContainer()); //create dynamic run configs ArrayOfString keys = runConfigs.keys(); for (int i = 0; i < keys.length(); i++) { String key = keys.get(i); final RunConfiguration runConfig = runConfigs.get(key); String label = runConfig.getLabel(); if (label == null) { //no label; this run config modifies hardcoded configs }else { //create an input radio, and possibly inject extra controls elemental.html.DivElement el = Elements.createDivElement(); elemental.html.InputElement input = Elements.createInputElement( resources.baseCss().radio() +" "+resources.runButtonTargetPopupCss().radio() ); input.setId(DOM.createUniqueId()); input.setType("radio"); input.setName("runType"); inputs.put(key, input); elemental.html.DivElement body = Elements.createDivElement(resources.runButtonTargetPopupCss().stackedContainer()); body.setInnerHTML("<div><label>"+label+"</label></div>"); ((elemental.html.LabelElement)body.getFirstChildElement().getFirstChildElement()).setHtmlFor(input.getId()); //now, add pluggable forms, if any, for the runtarget elemental.dom.Element extra = runConfig.getForm(); if (extra!=null) { body.appendChild(extra); } input.addEventListener(Event.CHANGE, new EventListener() { @Override public void handleEvent(Event evt) { if (getDelegate() != null) { getDelegate().onItemChanged(runConfig); } } },true); el.appendChild(input); el.appendChild(body); Elements.asJsElement(container).appendChild(el); } } setDisplayForRunningApp(RunTargetType.FILE); attachHandlers(); } public void attachHandlers() { runAlwaysDropdown.getInput().addEventListener(Event.INPUT, new EventListener() { @Override public void handleEvent(Event evt) { if (getDelegate() != null) { getDelegate().onAlwaysRunInputChanged(); } } }, false); Elements.asJsElement(userExtraInput).addEventListener(Event.INPUT, new EventListener() { @Override public void handleEvent(Event evt) { if (getDelegate() != null) { getDelegate().onPathInputChanged(); } } }, false); EventListener onEnterListener = new EventListener() { @Override public void handleEvent(Event evt) { if (getDelegate() != null) { KeyboardEvent keyEvent = (KeyboardEvent) evt; if (keyEvent.getKeyCode() == KeyboardEvent.KeyCode.ENTER) { getDelegate().onPathInputChanged(); evt.stopPropagation(); hide(); } //TODO(james) listen for down key, and load more results when at bottom of list } } }; runAlwaysDropdown.getInput().addEventListener(Event.KEYUP, onEnterListener, false); Elements.asJsElement(userExtraInput).addEventListener(Event.KEYUP, onEnterListener, false); } /** * Sets up the view based on the user's current file input value. */ public void setDisplayForRunningApp() { RunTargetType type = RunTargetType.parseTargetType(runAlwaysDropdown.getInput().getValue()); setDisplayForRunningApp(type); } /** * Sets up the view for the supplied app type. */ public void setDisplayForRunningApp(RunTargetType appType) { userExtraInput.setAttribute("placeholder", appType.placeHolder); userExtraLabel.setInnerText(appType.label); String fileName = runAlwaysDropdown.getInput().getValue(); String queryText = userExtraInput.getValue(); if (fileName.isEmpty()) { runHintText.setInnerText("Type a filename"); } else { runHintText.setInnerText(appType.inputFormatter.formatUserInput(fileName, queryText)); } } } public void renderPlugins() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/PopupBlockedInstructionalPopup.java
client/src/main/java/com/google/collide/client/workspace/PopupBlockedInstructionalPopup.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import collide.client.common.CommonResources; import collide.client.util.Elements; import com.google.collide.client.ui.popup.CenterPanel; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.Element; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; import elemental.events.Event; import elemental.events.EventListener; /** * Instructional popup that alert users that window with started application * has been blocked by browser. */ public class PopupBlockedInstructionalPopup extends UiComponent<PopupBlockedInstructionalPopup.View> { /** * Static factory method for obtaining an instance of the * {@link PopupBlockedInstructionalPopup}. */ public static PopupBlockedInstructionalPopup create(Resources res) { View view = new View(res); CenterPanel centerPanel = CenterPanel.create(res, view.getElement()); centerPanel.setHideOnEscapeEnabled(true); return new PopupBlockedInstructionalPopup(view, centerPanel); } /** * CSS resources interface. */ public interface Css extends CssResource { String root(); String popupBlockedIcon(); } /** * BaseResources interface. */ public interface Resources extends CommonResources.BaseResources, CenterPanel.Resources { @Source("PopupBlockedInstructionalPopup.css") Css popupBlockedInstructionalPopupCss(); @Source("blocked_popups.png") ImageResource popupBlockedIcon(); } interface ViewEvents { void onDoneClicked(); } static class View extends CompositeView<ViewEvents> { @UiTemplate("PopupBlockedInstructionalPopup.ui.xml") interface MyBinder extends UiBinder<Element, View> { } private static MyBinder uiBinder = GWT.create(MyBinder.class); final Resources res; @UiField(provided = true) final CommonResources.BaseCss baseCss; @UiField(provided = true) final Css css; @UiField AnchorElement doneButton; View(Resources res) { this.res = res; this.baseCss = res.baseCss(); this.css = res.popupBlockedInstructionalPopupCss(); setElement(Elements.asJsElement(uiBinder.createAndBindUi(this))); attachEventListeners(); } private void attachEventListeners() { Elements.asJsElement(doneButton).setOnclick(new EventListener() { @Override public void handleEvent(Event evt) { if (getDelegate() == null) { return; } getDelegate().onDoneClicked(); } }); } } class ViewEventsImpl implements ViewEvents { @Override public void onDoneClicked() { centerPanel.hide(); } } private final CenterPanel centerPanel; PopupBlockedInstructionalPopup(View view, CenterPanel centerPanel) { super(view); this.centerPanel = centerPanel; view.setDelegate(new ViewEventsImpl()); } public void show() { centerPanel.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/com/google/collide/client/workspace/UnauthorizedUser.java
client/src/main/java/com/google/collide/client/workspace/UnauthorizedUser.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import collide.client.common.CommonResources; import collide.client.util.Elements; import com.google.collide.client.bootstrap.BootstrapSession; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.SpanElement; 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; /** * Presenter for the message displayed to a user that accesses a workspace he is * not authorized to view. */ public class UnauthorizedUser extends UiComponent<UnauthorizedUser.View> { /** * Static factory method for {@link HeaderMenu}. */ public static UnauthorizedUser create(Resources res) { return new UnauthorizedUser(new View(res)); } /** * Style names. */ public interface Css extends CssResource { String base(); String title(); String email(); } /** * Images and CssResources. */ public interface Resources extends CommonResources.BaseResources { @Source({"UnauthorizedUser.css", "collide/client/common/constants.css"}) Css unauthorizedUserCss(); } /** * The View for the Header. */ public static class View extends CompositeView<ViewEvents> { @UiTemplate("UnauthorizedUser.ui.xml") interface MyBinder extends UiBinder<DivElement, View> { } static MyBinder binder = GWT.create(MyBinder.class); @UiField(provided = true) final Resources res; @UiField SpanElement email; public View(Resources res) { this.res = res; setElement(Elements.asJsElement(binder.createAndBindUi(this))); // Set the user's email/name. String userEmail = BootstrapSession.getBootstrapSession().getUsername(); Elements.asJsElement(email).setTextContent(userEmail); // Wire up event handlers. attachHandlers(); } protected void attachHandlers() { } } /** * Events reported by the Header's View. */ private interface ViewEvents { } private UnauthorizedUser(View view) { super(view); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/WorkspaceReadOnlyChangedEvent.java
client/src/main/java/com/google/collide/client/workspace/WorkspaceReadOnlyChangedEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * Event that is fired within a {@link WorkspacePlace} to notify all listeners * that the workspace has been opened in read only mode. */ public class WorkspaceReadOnlyChangedEvent extends GwtEvent<WorkspaceReadOnlyChangedEvent.Handler> { public interface Handler extends EventHandler { void onWorkspaceReadOnlyChanged(WorkspaceReadOnlyChangedEvent event); } public static final Type<Handler> TYPE = new Type<Handler>(); private boolean isReadOnly; public WorkspaceReadOnlyChangedEvent(boolean isReadOnly) { this.isReadOnly = isReadOnly; } public boolean isReadOnly() { return isReadOnly; } @Override protected void dispatch(Handler handler) { handler.onWorkspaceReadOnlyChanged(this); } @Override public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() { return TYPE; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/Header.java
client/src/main/java/com/google/collide/client/workspace/Header.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import collide.client.filetree.FileTreeModel; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.AppContext; import com.google.collide.client.bootstrap.BootstrapSession; import com.google.collide.client.history.Place; import com.google.collide.client.plugin.ClientPlugin; import com.google.collide.client.plugin.ClientPluginService; import com.google.collide.client.search.FileNameSearch; import com.google.collide.client.search.SearchContainer; import com.google.collide.client.search.awesomebox.AwesomeBox; import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponent; import com.google.collide.client.search.awesomebox.host.AwesomeBoxComponentHost; import com.google.collide.client.search.awesomebox.shared.AwesomeBoxResources; import com.google.collide.client.testing.DebugAttributeSetter; import com.google.collide.client.testing.DebugId; import com.google.collide.client.ui.button.ImageButton; import com.google.collide.client.ui.menu.PositionController.HorizontalAlign; import com.google.collide.client.ui.menu.PositionController.Positioner; import com.google.collide.client.ui.menu.PositionController.VerticalAlign; import com.google.collide.client.ui.tooltip.Tooltip; import com.google.collide.clientlibs.model.Workspace; import com.google.collide.dto.UserDetails; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import elemental.events.Event; import elemental.events.EventListener; import elemental.html.ImageElement; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.AnchorElement; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Element; import com.google.gwt.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; /** * The Header for the workspace Shell. * */ public class Header extends UiComponent<Header.View> { /** * Creates the default version of the header to be used in the editor shell. */ public static Header create(View view, WorkspaceShell.View workspaceShellView, Place currentPlace, final AppContext appContext, FileNameSearch fileNameSearch, FileTreeModel fileTreeModel) { AwesomeBoxComponentHost awesomeBoxHost = new AwesomeBoxComponentHost( view.awesomeBoxComponentHostView, appContext.getAwesomeBoxComponentHostModel()); // TODO: Sigh, due to tooltip being part of the client glob this // lives outside of the component host, need to resolve this when I get a // chance should be easy to make tooltip and autohide crud its own thing. // TODO: This should never be shown (its a fallback just in // case we hit a case where it could in the future). final String defaultText = "Access the AwesomeBox for more options"; Positioner tooltipPositioner = new Tooltip.TooltipPositionerBuilder().buildAnchorPositioner( view.awesomeBoxComponentHostView.getElement()); Tooltip tooltip = new Tooltip.Builder(appContext.getResources(), view.awesomeBoxComponentHostView.getElement(), tooltipPositioner).setTooltipRenderer( new Tooltip.TooltipRenderer() { @Override public elemental.dom.Element renderDom() { elemental.html.DivElement element = Elements.createDivElement(); AwesomeBoxComponent component = appContext.getAwesomeBoxComponentHostModel().getActiveComponent(); if (component == null || component.getTooltipText() == null) { element.setTextContent(defaultText); } else { element.setTextContent(component.getTooltipText()); } return element; } }).build(); AwesomeBox awesomeBoxComponent = AwesomeBox.create(appContext); appContext.getAwesomeBoxComponentHostModel().setDefaultComponent(awesomeBoxComponent); RunButtonController runButtonController = RunButtonController.create(appContext, view.runButton, view.runDropdownButton, currentPlace, fileNameSearch, fileTreeModel); Header header = new Header(view, currentPlace, appContext, runButtonController, awesomeBoxHost); return header; } /** * Style names associated with elements in the header. */ public interface Css extends CssResource { String gray(); String leftButtonGroup(); String pluginButtonContainer(); String paddedButton(); String pluginButtons(); String pluginIcon(); String pluginButton(); String runButtonContainer(); String runButton(); String runDropdownButton(); String runIcon(); String syncButtons(); String readOnlyMessage(); String newWorkspaceButton(); String selectArrows(); String selectBg(); String triangle(); String awesomeBoxContainer(); String feedbackButton(); String shareButton(); String rightButtonGroup(); String profileImage(); } /** * Images and CssResources consumed by the Header. */ public interface Resources extends AwesomeBox.Resources, AwesomeBoxResources, PopupBlockedInstructionalPopup.Resources, RunButtonTargetPopup.Resources, SearchContainer.Resources{ @Source("gear.png") ImageResource gearIcon(); @Source("gwt.png") ImageResource gwtIcon(); @Source("xapi.png") ImageResource xapiIcon(); @Source("terminal.png") ImageResource terminalIcon(); @Source("play.png") ImageResource runIcon(); @Source("play_dropdown.png") ImageResource runDropdownIcon(); @Source("select_control.png") ImageResource selectArrows(); @Source("read_only_message_icon.png") ImageResource readOnlyMessageIcon(); @Source("trunk_branch_icon.png") ImageResource trunkBranchIcon(); @Source({"Header.css", "constants.css", "collide/client/common/constants.css"}) Css workspaceHeaderCss(); } /** * The View for the Header. */ public static class View extends CompositeView<ViewEvents> { @UiTemplate("Header.ui.xml") interface MyBinder extends UiBinder<DivElement, View> { } static MyBinder binder = GWT.create(MyBinder.class); @UiField(provided = true) final Resources res; final Css css; @UiField DivElement headerMenuElem; @UiField DivElement pluginContainer; @UiField DivElement rightButtons; @UiField AnchorElement runButton; @UiField AnchorElement runDropdownButton; @UiField DivElement leftButtonGroup; @UiField DivElement syncButtonsDiv; @UiField DivElement readOnlyMessage; @UiField AnchorElement newWorkspaceButton; @UiField DivElement awesomeBoxContainer; @UiField AnchorElement feedbackButton; @UiField AnchorElement shareButton; @UiField DivElement profileImage; private final AwesomeBoxComponentHost.View awesomeBoxComponentHostView; private final ImageButton runImageButton; private final ImageButton runDropdownImageButton; private final ImageButton newWorkspaceImageButton; private final ImageButton shareImageButton; private final Tooltip newWorkspaceTooltip; public View(Resources res, boolean detached) { this.res = res; this.css = res.workspaceHeaderCss(); setElement(Elements.asJsElement(binder.createAndBindUi(this))); // Determine if we should use the awesome box awesomeBoxComponentHostView = new AwesomeBoxComponentHost.View(Elements.asJsElement( awesomeBoxContainer), res.awesomeBoxHostCss()); // Create the run button. runImageButton = new ImageButton.Builder(res).setImage(res.runIcon()) .setElement((elemental.html.AnchorElement) runButton).build(); runImageButton.getView().getImageElement().addClassName(res.workspaceHeaderCss().runIcon()); if (detached) { CssUtils.setDisplayVisibility2(Elements.asJsElement(rightButtons), false); } //install our plugins ClientPlugin<?>[] plugins = ClientPluginService.getPlugins(); ImageButton[] buttons = new ImageButton[plugins.length]; for (int i = 0; i < plugins.length; i++) { final ClientPlugin<?> plugin = plugins[i]; elemental.dom.Element holder = Elements.createDivElement( res.workspaceHeaderCss().pluginButtonContainer() ,res.workspaceHeaderCss().paddedButton() ); (Elements.asJsElement(pluginContainer)).appendChild(holder); elemental.dom.Element link = Elements.createElement("a",res.workspaceHeaderCss().pluginButton()); holder.getStyle().setWidth(60,"px"); link.getStyle().setLeft(i*40,"px"); holder.appendChild(link); final ImageButton button = new ImageButton.Builder(res).setImage(plugins[i].getIcon(res)) .setElement((elemental.html.AnchorElement) link).build(); buttons[i] = button; button.getView().getImageElement().addClassName(res.workspaceHeaderCss().pluginIcon()); button.setListener(() -> { if (getDelegate() != null) { getDelegate().onPluginButtonClicked(plugin, button); } }); } // Create the gear button. // Create the terminal button // terminalImageButton = new ImageButton.Builder(res).setImage(res.terminalIcon()) // .setElement((elemental.html.AnchorElement) terminalButton).build(); // terminalImageButton.getView().getImageElement().addClassName(res.workspaceHeaderCss().terminalIcon()); newWorkspaceImageButton = new ImageButton.Builder(res).setImage(res.trunkBranchIcon()) .setElement((elemental.html.AnchorElement) newWorkspaceButton).setText("Branch & Edit") .build(); newWorkspaceImageButton.getView() .getImageElement().addClassName(res.workspaceHeaderCss().newWorkspaceButton()); new ImageButton.Builder(res).setImage(res.readOnlyMessageIcon()) .setElement((elemental.html.AnchorElement) readOnlyMessage).setText("Read Only").build(); // Create the run drop down button. runDropdownImageButton = new ImageButton.Builder(res).setImage(res.runDropdownIcon()) .setElement((elemental.html.AnchorElement) runDropdownButton).build(); // Create the share button. Wait to set the icon until we know the // workspace's visibility // settings. shareImageButton = new ImageButton.Builder(res).setText("Share") .setElement((elemental.html.AnchorElement) shareButton).build(); setShareButtonVisible(true); new DebugAttributeSetter().setId(DebugId.WORKSPACE_HEADER_SHARE_BUTTON) .on(shareImageButton.getView().getElement()); // Tooltips Tooltip.create(res, Elements.asJsElement(runButton), VerticalAlign.BOTTOM, HorizontalAlign.MIDDLE, "Preview file or application"); Tooltip.create(res, Elements.asJsElement(runDropdownButton), VerticalAlign.BOTTOM, HorizontalAlign.MIDDLE, "Set custom preview target"); newWorkspaceTooltip = Tooltip.create(res, Elements.asJsElement(newWorkspaceButton), VerticalAlign.BOTTOM, HorizontalAlign.MIDDLE, "In Collide, code changes happen in branches.", "Click here to create your own editable branch of the top-level project source code."); newWorkspaceTooltip.setMaxWidth("150px"); // Wire up event handlers. attachHandlers(); CssUtils.setDisplayVisibility2(Elements.asJsElement(feedbackButton), false); CssUtils.setDisplayVisibility2(Elements.asJsElement(shareButton), false); } public AwesomeBoxComponentHost.View getAwesomeBoxView() { return awesomeBoxComponentHostView; } public DivElement getAwesomeBoxContainer() { return awesomeBoxContainer; } public void createReadOnlyMessageTooltip(Workspace workspace) { // boolean isTrunk = WorkspaceType.TRUNK == workspace.getWorkspaceType(); // String text; // if (isTrunk) { // text = "Click 'Branch & Edit' to make changes to Trunk"; // } else if (WorkspaceType.SUBMITTED == workspace.getWorkspaceType()) { // text = "This branch has been submitted to trunk and cannot be modified"; // } else { // text = "You have read access to this branch. Contact the owner to gain contributor access."; // } // Tooltip readOnlyMessageTooltip = Tooltip.create( // res, Elements.asJsElement(readOnlyMessage), VerticalAlign.BOTTOM, HorizontalAlign.MIDDLE, // text); // if (isTrunk) { // readOnlyMessageTooltip.setMaxWidth("150px"); // } } protected void attachHandlers() { runImageButton.setListener(new ImageButton.Listener() { @Override public void onClick() { if (getDelegate() != null) { getDelegate().onRunButtonClicked(); } } }); runDropdownImageButton.setListener(new ImageButton.Listener() { @Override public void onClick() { if (getDelegate() != null) { getDelegate().onRunDropdownButtonClicked(); } } }); shareImageButton.setListener(new ImageButton.Listener() { @Override public void onClick() { if (getDelegate() != null) { getDelegate().onShareButtonClicked(); } } }); getElement().setOnclick(new EventListener() { @Override public void handleEvent(Event evt) { ViewEvents delegate = getDelegate(); if (delegate == null) { return; } Element target = (Element) evt.getTarget(); if (feedbackButton.isOrHasChild(target)) { delegate.onFeedbackButtonClicked(); } else if (newWorkspaceButton.isOrHasChild(target)) { delegate.onNewWorkspaceButtonClicked(); } } }); } void setReadOnly(boolean isReadOnly) { if (isReadOnly) { CssUtils.setDisplayVisibility2( Elements.asJsElement(readOnlyMessage), true, false, "inline-block"); } else { CssUtils.setDisplayVisibility2(Elements.asJsElement(readOnlyMessage), false); } } public void setShareButtonVisible(boolean isVisible) { CssUtils.setDisplayVisibility2(Elements.asJsElement(shareButton), isVisible); } public void setRunButtonVisible(boolean isVisible) { CssUtils.setDisplayVisibility2(Elements.asJsElement(runButton), isVisible); CssUtils.setDisplayVisibility2(Elements.asJsElement(runDropdownButton), isVisible); } public Element getProfileImage() { return profileImage; } } /** * Events reported by the Header's View. */ private interface ViewEvents { void onPluginButtonClicked(ClientPlugin<?> plugin, ImageButton button); void onRunButtonClicked(); void onRunDropdownButtonClicked(); void onFeedbackButtonClicked(); void onShareButtonClicked(); void onNewWorkspaceButtonClicked(); } /** * The delegate implementation for handling events reported by the View. */ private class ViewEventsImpl implements ViewEvents { @Override public void onRunButtonClicked() { runButtonController.onRunButtonClicked(); } @Override public void onRunDropdownButtonClicked() { runButtonController.onRunButtonDropdownClicked(); } @Override public void onPluginButtonClicked(ClientPlugin<?> plugin, ImageButton button) { plugin.onClicked(button); } @Override public void onFeedbackButtonClicked() { // TODO: something. } @Override public void onShareButtonClicked() { } @Override public void onNewWorkspaceButtonClicked() { // was new workspace overlay } } private final AwesomeBoxComponentHost awesomeBoxComponentHost; private final RunButtonController runButtonController; private static final int PORTRAIT_SIZE_HEADER = 28; private Header(View view, Place currentPlace, AppContext appContext, RunButtonController runButtonController, AwesomeBoxComponentHost awesomeBoxComponentHost) { super(view); this.runButtonController = runButtonController; this.awesomeBoxComponentHost = awesomeBoxComponentHost; setProfileImage(); view.setDelegate(new ViewEventsImpl()); } public AwesomeBoxComponentHost getAwesomeBoxComponentHost() { return awesomeBoxComponentHost; } private void setProfileImage() { String url = BootstrapSession.getBootstrapSession().getProfileImageUrl(); if (url == null) return; ImageElement pic = Elements.createImageElement(getView().css.profileImage()); pic.setSrc(UserDetails.Utils.getSizeSpecificPortraitUrl( url , PORTRAIT_SIZE_HEADER)); Elements.asJsElement(getView().getProfileImage()).appendChild(pic); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/UploadClickedEvent.java
client/src/main/java/com/google/collide/client/workspace/UploadClickedEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import com.google.collide.client.util.PathUtil; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * Simple event that is fired within a {@link WorkspacePlace} when the user * clicks on the "upload" menu item(s). * */ public class UploadClickedEvent extends GwtEvent<UploadClickedEvent.Handler> { public interface Handler extends EventHandler { void onUploadClicked(UploadClickedEvent evt); } public enum UploadType { FILE, ZIP, DIRECTORY } public static final Type<Handler> TYPE = new Type<Handler>(); private final UploadType uploadType; private final PathUtil targetPath; public UploadClickedEvent(UploadType uploadType, PathUtil targetPath) { this.uploadType = uploadType; this.targetPath = targetPath; } @Override public Type<Handler> getAssociatedType() { return TYPE; } public PathUtil getTargetPath() { return targetPath; } public UploadType getUploadType() { return uploadType; } @Override protected void dispatch(Handler handler) { handler.onUploadClicked(this); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/WorkspacePlace.java
client/src/main/java/com/google/collide/client/workspace/WorkspacePlace.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import com.google.collide.client.history.Place; import com.google.collide.client.history.PlaceConstants; import com.google.collide.client.history.PlaceNavigationEvent; import com.google.collide.json.client.JsoStringMap; import com.google.collide.json.shared.JsonStringMap; /** * {@link Place} for arriving at the Workspace. */ public class WorkspacePlace extends Place { /** * The event that gets dispatched in order to arrive at the Workspace. * * @See {@link WorkspacePlaceNavigationHandler}. */ public class NavigationEvent extends PlaceNavigationEvent<WorkspacePlace> { public static final String NAV_EXPAND = "navEx"; private final boolean forceReload; private final boolean shouldNavExpand; public NavigationEvent(boolean shouldNavExpand, boolean forceReload) { super(WorkspacePlace.this); this.forceReload = forceReload; this.shouldNavExpand = shouldNavExpand; } @Override public JsonStringMap<String> getBookmarkableState() { JsoStringMap<String> state = JsoStringMap.create(); if (!shouldNavExpand) { state.put(NAV_EXPAND, String.valueOf(shouldNavExpand)); } return state; } public boolean shouldNavExpand() { return shouldNavExpand; } public boolean shouldForceReload() { return forceReload; } } public static final WorkspacePlace PLACE = new WorkspacePlace(); protected WorkspacePlace() { super(PlaceConstants.WORKSPACE_PLACE_NAME); } @Override public PlaceNavigationEvent<WorkspacePlace> createNavigationEvent( JsonStringMap<String> decodedState) { String shouldNavExpandString = decodedState.get(NavigationEvent.NAV_EXPAND); boolean shouldNavExpand = shouldNavExpandString == null ? true : Boolean.parseBoolean(shouldNavExpandString); return createNavigationEvent(shouldNavExpand, false); } public PlaceNavigationEvent<WorkspacePlace> createNavigationEvent(boolean shouldNavExpand) { return createNavigationEvent(shouldNavExpand, false); } @Override public PlaceNavigationEvent<WorkspacePlace> createNavigationEvent() { return new NavigationEvent(true, false); } public PlaceNavigationEvent<WorkspacePlace> createNavigationEvent( boolean shouldNavExpand, boolean forceReload) { return new NavigationEvent(shouldNavExpand, forceReload); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/WorkspaceUtils.java
client/src/main/java/com/google/collide/client/workspace/WorkspaceUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import com.google.collide.client.code.FileSelectedPlace; import com.google.collide.client.history.HistoryUtils; import com.google.collide.client.history.PlaceNavigationEvent; import com.google.collide.client.util.PathUtil; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * Utility methods for Workspace operations. * */ public class WorkspaceUtils { /** * Builds a deep link to a workspace. */ public static String createLinkToWorkspace() { JsonArray<PlaceNavigationEvent<?>> history = JsonCollections.createArray(); history.add(WorkspacePlace.PLACE.createNavigationEvent()); return "#" + HistoryUtils.createHistoryString(history); } /** * Builds a deep link to a file given a workspace id and file path. */ public static String createDeepLinkToFile(PathUtil filePath) { JsonArray<PlaceNavigationEvent<?>> history = JsonCollections.createArray(); history.add(WorkspacePlace.PLACE.createNavigationEvent(true)); history.add(FileSelectedPlace.PLACE.createNavigationEvent(filePath)); return "#" + HistoryUtils.createHistoryString(history); } private WorkspaceUtils() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/WorkspaceShell.java
client/src/main/java/com/google/collide/client/workspace/WorkspaceShell.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import collide.client.util.Elements; import com.google.collide.client.code.CodePerspective; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import elemental.dom.Element; import elemental.html.DivElement; import com.google.gwt.core.client.GWT; import com.google.gwt.resources.client.CssResource; /** * Presenter for the top-level shell of the workspace. Nothing more than a * container for the {@link Header} and simple API for setting the panel element * for the currently active workspace Perspective. * */ public class WorkspaceShell extends UiComponent<WorkspaceShell.View> { /** * Static factory method for obtaining an instance of the Workspace Shell. */ public static WorkspaceShell create(View view, Header header) { return new WorkspaceShell(view, header); } /** * Style names used by the WorkspaceShell. */ public interface Css extends CssResource { String base(); String header(); String perspectivePanel(); } /** * CSS and images used by the WorkspaceShell. */ public interface Resources extends CodePerspective.Resources, UnauthorizedUser.Resources { @Source("WorkspaceShell.css") Css workspaceShellCss(); } /** * The View for the Shell. */ public static class View extends CompositeView<Void> { private final Header.View headerView; private final DivElement perspectivePanel; public View(WorkspaceShell.Resources res, boolean detached) { super(Elements.createDivElement(res.workspaceShellCss().base())); // Create DOM and instantiate sub-views. this.headerView = new Header.View(res, detached); this.headerView.getElement().addClassName(res.workspaceShellCss().header()); this.perspectivePanel = Elements.createDivElement(res.workspaceShellCss().perspectivePanel()); if (GWT.getModuleName().equals("Collide")) { this.perspectivePanel.getStyle().setTop("57px"); } Element elem = getElement(); elem.appendChild(headerView.getElement()); elem.appendChild(perspectivePanel); } public Header.View getHeaderView() { return headerView; } public DivElement getPerspectivePanel() { return perspectivePanel; } } final Header header; protected WorkspaceShell(View view, Header header) { super(view); this.header = header; } public Header getHeader() { return header; } public void setPerspective(Element perspectiveContents) { getView().perspectivePanel.setInnerHTML(""); getView().perspectivePanel.appendChild(perspectiveContents); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/RunButtonController.java
client/src/main/java/com/google/collide/client/workspace/RunButtonController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeNode; import collide.client.util.Elements; import com.google.collide.client.AppContext; import com.google.collide.client.code.FileSelectionController.FileOpenedEvent; import com.google.collide.client.communication.ResourceUriUtils; import com.google.collide.client.history.Place; import com.google.collide.client.plugin.ClientPlugin; import com.google.collide.client.plugin.ClientPluginService; import com.google.collide.client.plugin.RunConfiguration; import com.google.collide.client.search.FileNameSearch; import com.google.collide.client.ui.menu.AutoHideComponent.AutoHideHandler; import com.google.collide.client.ui.menu.PositionController.HorizontalAlign; import com.google.collide.client.ui.menu.PositionController.Positioner; import com.google.collide.client.ui.menu.PositionController.VerticalAlign; import com.google.collide.client.ui.tooltip.Tooltip; import com.google.collide.client.ui.tooltip.Tooltip.TooltipRenderer; import com.google.collide.client.util.PathUtil; import com.google.collide.client.workspace.RunButtonTargetPopup.RunTargetType; import com.google.collide.dto.RunTarget; import com.google.collide.dto.UpdateWorkspaceRunTargets; import com.google.collide.dto.client.DtoClientImpls.RunTargetImpl; import com.google.collide.dto.client.DtoClientImpls.UpdateWorkspaceRunTargetsImpl; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.StringUtils; import com.google.gwt.dom.client.Element; import elemental.css.CSSStyleDeclaration; import elemental.html.DivElement; import elemental.html.SpanElement; import elemental.util.Collections; import elemental.util.MapFromStringTo; /** * Controller for the behavior of the run button on the workspace header. */ public class RunButtonController { public static RunButtonController create(AppContext context, Element buttonElem, Element dropdownElem, Place currentPlace, FileNameSearch fileNameSearch, FileTreeModel fileTreeModel) { //initialize our run configs with any items added by plugins MapFromStringTo<RunConfiguration> runConfigs = Collections.mapFromStringTo(); for (ClientPlugin<?> p : ClientPluginService.getPlugins()) { RunConfiguration runConfig = p.getRunConfig(); if (runConfig != null) { runConfigs.put(runConfig.getId(), runConfig); } } RunButtonTargetPopup targetPopup = RunButtonTargetPopup.create(context, buttonElem, dropdownElem, fileNameSearch, runConfigs); elemental.dom.Element target = Elements.asJsElement(buttonElem); Positioner positioner = new Tooltip.TooltipPositionerBuilder().setVerticalAlign( VerticalAlign.BOTTOM) .setHorizontalAlign(HorizontalAlign.RIGHT).buildAnchorPositioner(target); Tooltip noFileSelectedTooltip = new Tooltip.Builder( context.getResources(), target, positioner).setShouldListenToHover(false) .setTooltipRenderer(new TooltipRenderer() { @Override public elemental.dom.Element renderDom() { DivElement container = Elements.createDivElement(); DivElement header = Elements.createDivElement(); header.setTextContent("No File Selected"); header.getStyle().setFontWeight(CSSStyleDeclaration.FontWeight.BOLDER); header.getStyle().setMarginBottom(5, CSSStyleDeclaration.Unit.PX); container.appendChild(header); DivElement text = Elements.createDivElement(); text.setTextContent( "Choose a file from the tree to preview it, or select a custom run target."); container.appendChild(text); return container; } }).build(); Tooltip yamlAddedTooltip = new Tooltip.Builder( context.getResources(), target, positioner).setShouldListenToHover(false) .setTooltipRenderer(new TooltipRenderer() { @Override public elemental.dom.Element renderDom() { DivElement container = Elements.createDivElement(); SpanElement text = Elements.createSpanElement(); text.setTextContent( "The run target has been set to your newly created app.yaml file. "); container.appendChild(text); // TODO: We'd like to offer an option to undo the // automatic setting of the run target, but I don't have time // to write a coach tips class right now and tool tips can't be // clicked. return container; } }).build(); Tooltip targetResetTooltip = new Tooltip.Builder( context.getResources(), target, positioner).setShouldListenToHover(false) .setTooltipRenderer(new TooltipRenderer() { @Override public elemental.dom.Element renderDom() { DivElement container = Elements.createDivElement(); SpanElement text = Elements.createSpanElement(); text.setTextContent( "You deleted your run target, the run button has been reset to preview " + "the active file."); container.appendChild(text); // TODO: We'd like to offer undo, but I don't have time // to write a coach tips class right now and tool tips can't be // clicked. return container; } }).build(); return new RunButtonController(context, dropdownElem, currentPlace, fileNameSearch, targetPopup, runConfigs, fileTreeModel, noFileSelectedTooltip, yamlAddedTooltip, targetResetTooltip); } /** * A listener which handles events in the file tree which may affect the current RunTarget. */ public class FileTreeChangeListener extends FileTreeModel.AbstractTreeModelChangeListener { @Override public void onNodeAdded(PathUtil parentDirPath, FileTreeNode newNode) { RunTarget currentTarget = targetPopup.getRunTarget(); if ("ALWAYS_RUN".equals(currentTarget.getRunMode()) && currentTarget.getAlwaysRunFilename().contains("app.yaml")) { return; } // did the user add an app.yaml? if (newNode.isFile() && newNode.getName().equals("app.yaml")) { // lets set the run target to run the app.yaml RunTarget target = RunTargetImpl.make().setRunMode("ALWAYS_RUN") .setAlwaysRunFilename(newNode.getNodePath().getPathString()).setAlwaysRunUrlOrQuery(""); updateRunTarget(target); targetPopup.setRunTarget(target); yamlSelectedFileTooltip.show(TOOLTIP_DISPLAY_TIMEOUT_MS); } } @Override public void onNodeMoved( PathUtil oldPath, FileTreeNode node, PathUtil newPath, FileTreeNode newNode) { RunTarget currentTarget = targetPopup.getRunTarget(); if (currentTarget == null || currentTarget.getAlwaysRunFilename() == null) { return; } PathUtil currentAlwaysRunPath = new PathUtil(currentTarget.getAlwaysRunFilename()); PathUtil relativePath = currentAlwaysRunPath.makeRelativeToParent(oldPath); if (relativePath != null) { // Either this node, or some ancestor node got renamed. PathUtil newFilePath = PathUtil.concatenate(newPath, relativePath); RunTargetImpl impl = (RunTargetImpl) currentTarget; impl.setAlwaysRunFilename(newFilePath.getPathString()); targetPopup.setRunTarget(impl); } } @Override public void onNodesRemoved(JsonArray<FileTreeNode> oldNodes) { RunTarget target = targetPopup.getRunTarget(); // we should clear the current file if the user deleted that one // we should revert the run target to preview if the user deleted the // "always run target". // If this gets more complicated, make it a visitor type thing boolean isAlwaysRun = "ALWAYS_RUN".equals(target.getRunMode()); boolean hasClearedCurrentFile = currentFilePath == null; boolean hasClearedAlwaysRun = !isAlwaysRun; PathUtil alwaysRunPath = isAlwaysRun ? new PathUtil(target.getAlwaysRunFilename()) : null; for (int i = 0; (!hasClearedCurrentFile || !hasClearedAlwaysRun) && i < oldNodes.size(); i++) { FileTreeNode node = oldNodes.get(i); if (!hasClearedCurrentFile) { if (node.getNodePath().containsPath(currentFilePath)) { updateCurrentFile(null); hasClearedCurrentFile = true; } } if (!hasClearedAlwaysRun) { if (node.getNodePath().containsPath(alwaysRunPath)) { RunTarget newTarget = RunTargetImpl.make().setRunMode("PREVIEW_CURRENT_FILE"); updateRunTarget(newTarget); targetResetTooltip.show(TOOLTIP_DISPLAY_TIMEOUT_MS); hasClearedAlwaysRun = true; } } } } } /** * Timeout for tooltip messages to the user. */ private static final int TOOLTIP_DISPLAY_TIMEOUT_MS = 5000; private final Place currentPlace; private final AppContext appContext; private final RunButtonTargetPopup targetPopup; private final Element dropdownElem; private final Tooltip noFileSelectedTooltip; private final Tooltip yamlSelectedFileTooltip; private final Tooltip targetResetTooltip; private final MapFromStringTo<RunConfiguration> runConfigs; private PathUtil currentFilePath; private RunButtonController(final AppContext appContext, Element dropdownElem, Place currentPlace, FileNameSearch fileNameSearch, final RunButtonTargetPopup targetPopup, final MapFromStringTo<RunConfiguration> runConfigs, FileTreeModel fileTreeModel, Tooltip noFileSelectedTooltip, Tooltip autoSelectedFileTooltip, Tooltip targetResetTooltip) { this.appContext = appContext; this.dropdownElem = dropdownElem; this.currentPlace = currentPlace; this.targetPopup = targetPopup; this.noFileSelectedTooltip = noFileSelectedTooltip; this.yamlSelectedFileTooltip = autoSelectedFileTooltip; this.targetResetTooltip = targetResetTooltip; this.runConfigs = runConfigs; //put in our hardcoded default configs if (!runConfigs.hasKey("PREVIEW_CURRENT_FILE")) runConfigs.put("PREVIEW_CURRENT_FILE", new RunConfiguration() { @Override public String getId() { return "PREVIEW_CURRENT_FILE"; } @Override public String getLabel() { return "View On Server"; } @Override public void run(AppContext appContext, PathUtil file) { launchFile(currentFilePath == null ? null : currentFilePath.getPathString(), ""); } @Override public elemental.dom.Element getForm() { return null; } }); // Setup handler to keep track of current file currentPlace.registerSimpleEventHandler(FileOpenedEvent.TYPE, new FileOpenedEvent.Handler() { @Override public void onFileOpened(boolean isEditable, PathUtil filePath) { updateCurrentFile(filePath); } }); // Listen to the file Tree fileTreeModel.addModelChangeListener(new FileTreeChangeListener()); this.targetPopup.setAutoHideHandler(new AutoHideHandler() { @Override public void onHide() { toggleDropdownStyle(false); // Update the runTarget for this workspace // TODO: Consider checking to see if there has actually // been a change RunTarget runTarget = targetPopup.getRunTarget(); updateRunTarget(runTarget); } @Override public void onShow() { // do nothing } }); } public void toggleDropdownStyle(boolean active) { if (active) { dropdownElem.addClassName(appContext.getResources().baseCss().buttonActive()); dropdownElem.addClassName(appContext.getResources().runButtonTargetPopupCss().stayActive()); } else { dropdownElem.removeClassName(appContext.getResources().baseCss().buttonActive()); dropdownElem.removeClassName( appContext.getResources().runButtonTargetPopupCss().stayActive()); } } public void onRunButtonClicked() { if (targetPopup.getRunTarget() != null) { launchRunTarget(targetPopup.getRunTarget()); } else { launchFile(currentFilePath == null ? null : currentFilePath.getPathString(), ""); } } private void launchRunTarget(RunTarget target) { RunConfiguration runner = runConfigs.get(target.getRunMode()); if (runner == null) { launchFile(target.getAlwaysRunFilename(), target.getAlwaysRunUrlOrQuery()); }else { runner.run(appContext, currentFilePath); } } /** * Launches a file using the appropriate method */ private void launchFile(String file, String urlOrQuery) { if (file == null) { displayNoFileSelectedTooltip(); return; } RunTargetType appType = RunButtonTargetPopup.RunTargetType.parseTargetType(file); launchPreview(file, StringUtils.nullToEmpty(urlOrQuery)); } public void onRunButtonDropdownClicked() { if (targetPopup.isShowing()) { targetPopup.forceHide(); } else { targetPopup.show(); // only needed on show since hiding is caught by the auto hide handler toggleDropdownStyle(true); } } private void updateRunTarget(RunTarget newTarget) { UpdateWorkspaceRunTargets update = UpdateWorkspaceRunTargetsImpl.make().setRunTarget(newTarget); appContext.getFrontendApi().UPDATE_WORKSPACE_RUN_TARGETS.send(update); targetPopup.setRunTarget(newTarget); } /** * Launches a file given the base file and a query string. */ public void launchPreview(String baseUrl, String query) { StringBuilder builder = new StringBuilder(ResourceUriUtils.getAbsoluteResourceBaseUri()); builder.append(StringUtils.ensureStartsWith(baseUrl, "/")); if (!StringUtils.isNullOrEmpty(query)) { builder.append(StringUtils.ensureStartsWith(query, "?")); } currentPlace.fireEvent(new RunApplicationEvent(builder.toString())); } private void updateCurrentFile(PathUtil filePath) { currentFilePath = filePath; targetPopup.updateCurrentFile(filePath == null ? null : filePath.getPathString()); } private void displayNoFileSelectedTooltip() { noFileSelectedTooltip.show(TOOLTIP_DISPLAY_TIMEOUT_MS); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/RunApplicationEvent.java
client/src/main/java/com/google/collide/client/workspace/RunApplicationEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * Event dispatched when the application should be run, for example when the run * button is clicked on a given workspace. */ public class RunApplicationEvent extends GwtEvent<RunApplicationEvent.Handler> { /** * Handler interface for getting notified when the run button in the Workspace * Header is clicked. */ public interface Handler extends EventHandler { void onRunButtonClicked(RunApplicationEvent evt); } public static final Type<Handler> TYPE = new Type<Handler>(); private final String url; public RunApplicationEvent(String url) { this.url = url; } @Override public Type<Handler> getAssociatedType() { return TYPE; } public String getUrl() { return url; } @Override protected void dispatch(Handler handler) { handler.onRunButtonClicked(this); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/KeepAliveTimer.java
client/src/main/java/com/google/collide/client/workspace/KeepAliveTimer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import com.google.collide.client.AppContext; import com.google.collide.client.util.logging.Log; import com.google.collide.dto.client.DtoClientImpls.KeepAliveImpl; import com.google.gwt.user.client.Timer; /** * Utility class for keep-alive timer inside of a workspace. * */ public class KeepAliveTimer { private final Timer timer; private final int keepAliveTimerIntervalMs; public KeepAliveTimer(final AppContext appContext, int keepAliveTimerIntervalMs) { this.keepAliveTimerIntervalMs = keepAliveTimerIntervalMs; if (keepAliveTimerIntervalMs > 0) { timer = new Timer() { @Override public void run() { appContext.getFrontendApi().KEEP_ALIVE.send(KeepAliveImpl.make()); } }; } else { timer = null; Log.warn(getClass(), "Keep-alive interval is not set."); } } public void start() { if (timer != null) { timer.scheduleRepeating(keepAliveTimerIntervalMs); } } public void cancel() { if (timer == null) { Log.warn(this.getClass(), "Client is leaving a workspace that has no keep-alive timer."); } else { timer.cancel(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/WorkspacePlaceNavigationHandler.java
client/src/main/java/com/google/collide/client/workspace/WorkspacePlaceNavigationHandler.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace; import collide.client.editor.DefaultEditorConfiguration; import collide.client.filetree.AppContextFileTreeController; import collide.client.filetree.FileTreeController; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeModelNetworkController; 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.NavigationAreaExpansionEvent; import com.google.collide.client.code.ParticipantModel; import com.google.collide.client.collaboration.CollaborationManager; import com.google.collide.client.collaboration.DocOpsSavedNotifier; import com.google.collide.client.collaboration.IncomingDocOpDemultiplexer; import com.google.collide.client.communication.FrontendApi.ApiCallback; import com.google.collide.client.document.DocumentManager; import com.google.collide.client.history.PlaceNavigationHandler; import com.google.collide.client.search.FileNameSearch; import com.google.collide.client.search.TreeWalkFileNameSearchImpl; import com.google.collide.client.ui.panel.MultiPanel; import com.google.collide.dto.GetWorkspaceMetaDataResponse; import com.google.collide.dto.ServerError.FailureReason; import com.google.collide.dto.client.DtoClientImpls.GetWorkspaceMetaDataImpl; import com.google.collide.shared.util.ListenerRegistrar.Remover; import com.google.collide.shared.util.ListenerRegistrar.RemoverManager; import com.google.gwt.core.client.Scheduler; import elemental.events.Event; import elemental.events.EventListener; import elemental.events.EventRemover; import elemental.events.KeyboardEvent; import elemental.events.KeyboardEvent.KeyCode; /** * Handler for the selection of a Workspace. */ // TODO: At some point we should try to make reEnter work on this thing. public class WorkspacePlaceNavigationHandler extends PlaceNavigationHandler<WorkspacePlace.NavigationEvent> { private final AppContext appContext; private final FileNameSearch searchIndex; private final RemoverManager keyListenerRemoverManager; // Presenters and Controllers that require cleanup. private Header header; private DocumentManager documentManager; private CollaborationManager collaborationManager; private WorkspacePlace workspacePlace; private WorkspaceShell shell; private FileTreeModelNetworkController fileNetworkController; private KeepAliveTimer keepAliveTimer; private ParticipantModel participantModel; private CodePanelBundle codePanelBundle; public WorkspacePlaceNavigationHandler(AppContext appContext) { this.appContext = appContext; this.keyListenerRemoverManager = new RemoverManager(); this.searchIndex = TreeWalkFileNameSearchImpl.create(); } @Override protected void cleanup() { if (codePanelBundle != null) { codePanelBundle.cleanup(); } if (collaborationManager != null) { collaborationManager.cleanup(); } if (documentManager != null) { documentManager.cleanup(); } if (keyListenerRemoverManager != null) { keyListenerRemoverManager.remove(); } if (keepAliveTimer != null) { keepAliveTimer.cancel(); } } @Override protected void enterPlace(final WorkspacePlace.NavigationEvent navigationEvent) { // Instantiate the Root View for the Workspace. final Resources res = appContext.getResources(); WorkspaceShell.View workspaceShellView = new WorkspaceShell.View(res, isDetached()); workspacePlace = navigationEvent.getPlace(); final FileTreeController<?> fileTreeController = new AppContextFileTreeController(appContext); FileTreeModelNetworkController.OutgoingController fileTreeModelOutgoingNetworkController = new FileTreeModelNetworkController.OutgoingController( fileTreeController); FileTreeModel fileTreeModel = new FileTreeModel(fileTreeModelOutgoingNetworkController); documentManager = DocumentManager.create(fileTreeModel, fileTreeController); searchIndex.setFileTreeModel(fileTreeModel); participantModel = ParticipantModel.create(appContext.getFrontendApi(), appContext.getMessageFilter()); IncomingDocOpDemultiplexer docOpRecipient = IncomingDocOpDemultiplexer.create(appContext.getMessageFilter()); collaborationManager = CollaborationManager.create(appContext, documentManager, participantModel, docOpRecipient); DocOpsSavedNotifier docOpSavedNotifier = new DocOpsSavedNotifier(documentManager, collaborationManager); fileNetworkController = FileTreeModelNetworkController.create(fileTreeModel, fileTreeController, navigationEvent.getPlace()); header = Header.create(workspaceShellView.getHeaderView(), workspaceShellView, workspacePlace, appContext, searchIndex, fileTreeModel); shell = WorkspaceShell.create(workspaceShellView, header); // Add a HotKey listener for to auto-focus the AwesomeBox. /* The GlobalHotKey stuff utilizes the wave signal event stuff which filters alt+enter as an unimportant * event. This prevents us from using the GlobalHotKey manager here. Note: This is capturing since the * editor likes to nom-nom keys, in the dart re-write lets think about this sort of stuff ahead of time. */ final EventRemover eventRemover = Elements.getBody().addEventListener(Event.KEYDOWN, new EventListener() { @Override public void handleEvent(Event evt) { KeyboardEvent event = (KeyboardEvent)evt; if (event.isAltKey() && event.getKeyCode() == KeyCode.ENTER) { appContext.getAwesomeBoxComponentHostModel().revertToDefaultComponent(); header.getAwesomeBoxComponentHost().show(); } } }, true); // Track this for removal in cleanup keyListenerRemoverManager.track(new Remover() { @Override public void remove() { eventRemover.remove(); } }); codePanelBundle = createCodePanelBundle(appContext, shell, fileTreeController, fileTreeModel, searchIndex, documentManager, participantModel, docOpRecipient, navigationEvent.getPlace()); codePanelBundle.attach(isDetached(), new DefaultEditorConfiguration()); codePanelBundle.setMasterPanel(createMasterPanel(res)); // Attach to the DOM. attachComponents(shell, header); // Reset the tab title Elements.setCollideTitle(""); if (!navigationEvent.shouldNavExpand()) { workspacePlace.fireEvent(new NavigationAreaExpansionEvent(false)); } // Send a message to enter the workspace and initialize the workspace. appContext.getFrontendApi().GET_WORKSPACE_META_DATA.send(GetWorkspaceMetaDataImpl.make(), new ApiCallback<GetWorkspaceMetaDataResponse>() { @Override public void onMessageReceived(GetWorkspaceMetaDataResponse message) { if (!navigationEvent.getPlace().isActive()) { return; } // Start the keep-alive timer at 10 second intervals. keepAliveTimer = new KeepAliveTimer(appContext, 5000); keepAliveTimer.start(); codePanelBundle.enterWorkspace(navigationEvent.isActiveLeaf(), navigationEvent.getPlace(), message); } @Override public void onFail(FailureReason reason) { if (FailureReason.UNAUTHORIZED == reason) { /* User is not authorized to access this workspace. At this point, the components of the * WorkspacePlace already sent multiple requests to the frontend that are bound to fail with the * same reason. However, we don't want to gate loading the workspace to handle the rare case that * a user accesses a branch that they do not have permission to access. Better to make the * workspace load fast and log errors if the user is not authorized. */ UnauthorizedUser unauthorizedUser = UnauthorizedUser.create(res); shell.setPerspective(unauthorizedUser.getView().getElement()); } } }); } protected boolean isDetached() { return false; } protected CodePanelBundle createCodePanelBundle(AppContext appContext, WorkspaceShell shell, FileTreeController<?> fileTreeController, FileTreeModel fileTreeModel, FileNameSearch searchIndex, DocumentManager documentManager, ParticipantModel participantModel, IncomingDocOpDemultiplexer docOpRecipient, WorkspacePlace place) { return new CodePanelBundle(appContext, shell, fileTreeController, fileTreeModel, searchIndex, documentManager, participantModel, docOpRecipient, place); } protected void attachComponents(WorkspaceShell shell, Header header) { Elements.replaceContents(AppContext.GWT_ROOT, shell.getView().getElement()); } @Override protected void reEnterPlace(final WorkspacePlace.NavigationEvent navigationEvent, boolean hasNewState) { if (hasNewState || navigationEvent.shouldForceReload()) { // Simply do the default action which is to run cleanup/enter. super.reEnterPlace(navigationEvent, hasNewState); } else { // we check to see if we end up being the active leaf and if so show the // no file selected panel. Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() { @Override public void execute() { if (navigationEvent.isActiveLeaf()) { onNoFileSelected(); } } }); } } protected void onNoFileSelected() { codePanelBundle.showNoFileSelectedPanel(); } protected MultiPanel<?,?> createMasterPanel(Resources resources) { return codePanelBundle.contentArea; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineNodeRenderer.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineNodeRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import collide.client.treeview.NodeRenderer; import collide.client.treeview.TreeNodeElement; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import elemental.dom.Element; import elemental.html.DivElement; import elemental.html.SpanElement; /** * Class used by tree component to produce visual elements. */ public class OutlineNodeRenderer implements NodeRenderer<OutlineNode> { private static final int LABEL_NODE_INDEX = 1; /** * Style names associated with elements in the outline node. */ public interface Css extends CssResource { String root(); String icon(); String clazz(); String function(); String cssClazz(); String jsField(); String label(); String disabled(); } /** * CSS and images used by the OutlineNodeRenderer. */ public interface Resources extends ClientBundle { @Source("clazz.png") ImageResource clazz(); @Source("function.png") ImageResource function(); @Source("css-clazz.png") ImageResource cssClazz(); @Source("js-field.png") ImageResource jsField(); @Source("OutlineNodeRenderer.css") Css workspaceNavigationOutlineNodeRendererCss(); } private final Css css; public OutlineNodeRenderer(Resources resources) { this.css = resources.workspaceNavigationOutlineNodeRendererCss(); } @Override public Element getNodeKeyTextContainer(SpanElement treeNodeLabel) { return (Element) treeNodeLabel.getChildNodes().item(LABEL_NODE_INDEX); } @SuppressWarnings("incomplete-switch") @Override public SpanElement renderNodeContents(OutlineNode data) { SpanElement root = Elements.createSpanElement(css.root()); DivElement icon = Elements.createDivElement(css.icon()); switch (data.getType()) { case CLASS: icon.addClassName(css.clazz()); break; case FUNCTION: icon.addClassName(css.function()); break; case FIELD: icon.addClassName(css.jsField()); break; case CSS_CLASS: icon.addClassName(css.cssClazz()); break; } SpanElement label = Elements.createSpanElement(css.label()); label.setTextContent(data.getName()); root.appendChild(icon); root.appendChild(label); CssUtils.setClassNameEnabled(label, css.disabled(), !data.isEnabled()); // TODO: replace with test case assert root.getChildNodes().item(LABEL_NODE_INDEX) == label; return root; } @Override public void updateNodeContents(TreeNodeElement<OutlineNode> treeNode) { // Not implemented. } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/CssOutlineParser.java
client/src/main/java/com/google/collide/client/workspace/outline/CssOutlineParser.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import static com.google.collide.client.workspace.outline.OutlineNode.OUTLINE_NODE_ANCHOR_TYPE; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.CSS_CLASS; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_LINE_NUMBER; import com.google.collide.client.documentparser.AsyncParser; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.codemirror2.CssToken; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; import com.google.common.base.Preconditions; /** * Parser for CSS files. * * Consumes tokens from codemirror2, produces OutlineNodes. */ public class CssOutlineParser extends AsyncParser<OutlineNode> implements OutlineParser { /** * Parent object that is notified, when parsing is complete. */ private final OutlineConsumer consumer; /** * Root node. * * Root node is created only once, updated by model. */ private final OutlineNode root; /** * Anchor that denotes a first position where we get "tag" or "atom" token. */ private Anchor tagAnchor; /** * Outline node name represented as array of strings. */ private JsonArray<String> tagName; /** * Flag that indicates, that there were unused space token. */ private boolean spaceBetween; /** * Handle for listener unregistration. */ private ListenerRegistrar.Remover listenerRemover; @Override public void onParseLine(Line line, int lineNumber, JsonArray<Token> tokens) { int column = 0; for (Token token : tokens.asIterable()) { TokenType type = token.getType(); String value = token.getValue(); column = column + value.length(); if (TokenType.WHITESPACE == type || TokenType.NEWLINE == type) { spaceBetween = true; continue; } if (TokenType.COMMENT == type || TokenType.VARIABLE == type || TokenType.NUMBER == type) { continue; } Preconditions.checkState(token instanceof CssToken, "Expected CssToken, but received %s", token); String context = ((CssToken) token).getContext(); boolean freeContext = context == null || "@media{".equals(context); if (!freeContext || ",".equals(value) || "}".equals(value) || "{".equals(value)) { // Node is finished, push it to the list. if (tagAnchor != null) { OutlineNode item = new OutlineNode(tagName.join(""), CSS_CLASS, root, lineNumber, 0); addData(item); item.setEnabled(true); item.setAnchor(tagAnchor); tagAnchor = null; tagName.clear(); } spaceBetween = false; } else { if (tagAnchor == null) { tagAnchor = line.getDocument().getAnchorManager().createAnchor( OUTLINE_NODE_ANCHOR_TYPE, line, IGNORE_LINE_NUMBER, column - value.length()); } if (spaceBetween && tagName.size() > 0) { tagName.add(" "); } spaceBetween = false; tagName.add(value); } } spaceBetween = true; } @Override public void onAfterParse(JsonArray<OutlineNode> nodes) { consumer.onOutlineParsed(nodes); } @Override public void onBeforeParse() { // TODO: restore tagName and tagAnchor tagName.clear(); spaceBetween = false; detachLastAnchor(); } private void detachLastAnchor() { if (tagAnchor != null) { if (tagAnchor.isAttached()) { tagAnchor.getLine().getDocument().getAnchorManager().removeAnchor(tagAnchor); } tagAnchor = null; } } @Override public void onCleanup(JsonArray<OutlineNode> nodes) { final int l = nodes.size(); if (l > 0) { AnchorManager anchorManager = nodes.get(0).getAnchor().getLine().getDocument().getAnchorManager(); for (int i = 0; i < l; i++) { Anchor anchor = nodes.get(i).getAnchor(); if (anchor.isAttached()) { anchorManager.removeAnchor(anchor); } } } } @Override public void cleanup() { super.cleanup(); detachLastAnchor(); listenerRemover.remove(); listenerRemover = null; } public CssOutlineParser(ListenerRegistrar<DocumentParser.Listener> parserListenerRegistrar, OutlineConsumer consumer) { this.consumer = consumer; listenerRemover = parserListenerRegistrar.add(this); root = new OutlineNode("css-root", OutlineNode.OutlineNodeType.ROOT, null, 0, 0); tagName = JsonCollections.createArray(); } @Override public OutlineNode getRoot() { return 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/com/google/collide/client/workspace/outline/OutlineConsumer.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineConsumer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import com.google.collide.json.shared.JsonArray; /** * Interface that represents {@link OutlineController} to outline producers. */ public interface OutlineConsumer { void onOutlineParsed(JsonArray<OutlineNode> nodes); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/AbstractOutlineBuilder.java
client/src/main/java/com/google/collide/client/workspace/outline/AbstractOutlineBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import com.google.collide.dto.CodeBlock; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Abstract implementation that holds shared code. */ public abstract class AbstractOutlineBuilder implements OutlineBuilder { /** * Array of generated nodes, sorted by line number. */ protected JsonArray<OutlineNode> allNodes; @Override public OutlineNode build(CodeBlock source, Document target) { Preconditions.checkNotNull(source); Preconditions.checkNotNull(target); Preconditions.checkArgument(source.getBlockType() == CodeBlock.Type.VALUE_FILE); allNodes = JsonCollections.createArray(); try { OutlineNode result = buildTree(source); bindNodes(target); return result; } finally { this.allNodes = null; } } protected abstract OutlineNode buildTree(CodeBlock source); /** * Bind allNodes to document lines. */ protected void bindNodes(Document target) { // At least root node is listed Preconditions.checkState(!allNodes.isEmpty()); AnchorManager anchorManager = target.getAnchorManager(); LineFinder lineFinder = target.getLineFinder(); LineInfo cursor = lineFinder.findLine(0); int lastLineNumber = target.getLastLineNumber(); for (int i = 0, size = allNodes.size(); i < size; ++i) { OutlineNode node = allNodes.get(i); int lineNumber = node.getLineNumber(); if (lineNumber > lastLineNumber) { break; } // TODO: we should create method that reuses cursor object! cursor = lineFinder.findLine(cursor, lineNumber); maybeBindNode(node, cursor.line(), anchorManager); } } /** * Check that line corresponds to node, and, if so, bind. */ protected abstract void maybeBindNode(OutlineNode node, Line line, AnchorManager anchorManager); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineController.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import static com.google.collide.shared.grok.GrokUtils.findFileCodeBlock; import collide.client.treeview.Tree; import collide.client.treeview.TreeNodeElement; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.client.codeunderstanding.CubeData; import com.google.collide.client.codeunderstanding.CubeDataUpdates; import com.google.collide.client.codeunderstanding.CubeUpdateListener; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.dto.CodeBlock; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.anchor.Anchor; import com.google.common.base.Preconditions; import elemental.js.html.JsDragEvent; /** * Controller object that is directly or indirectly notified about events * and performs corresponding over outline model. */ public class OutlineController implements CubeUpdateListener, Tree.Listener<OutlineNode>, OutlineConsumer { private final OutlineModel model; private final CubeClient cubeClient; private final Editor editor; private boolean acceptCubeUpdates; private OutlineParser currentOutlineParser; private OutlineBuilder currentOutlineBuilder; private final OutlineNode emptyRoot; public OutlineController(OutlineModel model, CubeClient cubeClient, Editor editor) { this.editor = editor; Preconditions.checkNotNull(model); Preconditions.checkNotNull(cubeClient); this.model = model; this.cubeClient = cubeClient; emptyRoot = new OutlineNode("empty-root", OutlineNode.OutlineNodeType.ROOT, null, 0, 0); } @Override public void onCubeResponse(CubeData data, CubeDataUpdates updates) { if (!acceptCubeUpdates) { return; } if (model.getRoot() != null && !updates.isFileTree()) { return; } updateFileTree(data); } private void updateFileTree(CubeData data) { Preconditions.checkNotNull(currentOutlineBuilder); CodeBlock fileTree = data.getFileTree(); if (fileTree == null) { fileTree = findFileCodeBlock(data.getFullGraph(), data.getFilePath()); } if (fileTree == null) { return; } Document document = editor.getDocument(); model.updateRoot(currentOutlineBuilder.build(fileTree, document), document); } public void cleanup() { if (acceptCubeUpdates) { cubeClient.removeListener(this); acceptCubeUpdates = false; } if (currentOutlineParser != null) { currentOutlineParser.cleanup(); currentOutlineParser = null; } model.setListener(null); model.cleanup(); } public void onDocumentChanged(DocumentParser parser) { model.cleanup(); SyntaxType syntax = (parser != null) ? parser.getSyntaxType() : SyntaxType.NONE; boolean oldAcceptCubeUpdates = acceptCubeUpdates; if (currentOutlineParser != null) { currentOutlineParser.cleanup(); currentOutlineParser = null; } switch (syntax) { case JS: currentOutlineBuilder = new JsOutlineBuilder(); acceptCubeUpdates = true; break; case PY: currentOutlineBuilder = new PyOutlineBuilder(); acceptCubeUpdates = true; break; case CSS: acceptCubeUpdates = false; currentOutlineParser = new CssOutlineParser(parser.getListenerRegistrar(), this); model.updateRoot(currentOutlineParser.getRoot(), editor.getDocument()); break; default: acceptCubeUpdates = false; model.updateRoot(emptyRoot, editor.getDocument()); } if (acceptCubeUpdates != oldAcceptCubeUpdates) { if (acceptCubeUpdates) { cubeClient.addListener(this); } else { cubeClient.removeListener(this); } } if (acceptCubeUpdates) { updateFileTree(cubeClient.getData()); } } @Override public void onNodeAction(TreeNodeElement<OutlineNode> node) { OutlineNode data = node.getData(); Anchor anchor = data.getAnchor(); if (anchor == null) { return; } if (anchor.isAttached()) { // TODO: check that item is still there, // see comments in OutlineNodeBuilder. Line line = anchor.getLine(); if (line.getText().contains(data.getName())) { editor.getFocusManager().focus(); LineFinder lineFinder = editor.getDocument().getLineFinder(); editor.scrollTo(lineFinder.findLine(line).number(), anchor.getColumn()); return; } } // If we didn't find what we were looking for, then: // 1) render node as disabled model.setDisabled(data); // TODO: 2) schedule navigation for next data update } @Override public void onNodeClosed(TreeNodeElement<OutlineNode> node) { // do nothing } @Override public void onNodeContextMenu(int mouseX, int mouseY, TreeNodeElement<OutlineNode> node) { // do nothing } @Override public void onNodeDragDrop(TreeNodeElement<OutlineNode> node, JsDragEvent event) { // do nothing } @Override public void onRootDragDrop(JsDragEvent event) { // do nothing } @Override public void onNodeExpanded(TreeNodeElement<OutlineNode> node) { // do nothing } @Override public void onRootContextMenu(int mouseX, int mouseY) { // do nothing } @Override public void onOutlineParsed(JsonArray<OutlineNode> nodes) { if (acceptCubeUpdates) { return; } model.setRootChildren(nodes); } @Override public void onNodeDragStart(TreeNodeElement<OutlineNode> node, JsDragEvent event) { // do nothing } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineNode.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineNode.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import collide.client.treeview.TreeNodeElement; import com.google.collide.client.documentparser.AsyncParser; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Data class containing information about file structure node and some renderer-specific * information. * */ public class OutlineNode implements AsyncParser.LineAware { public static final AnchorType OUTLINE_NODE_ANCHOR_TYPE = AnchorType.create( OutlineNode.class, "outlineNode"); /** * Types of structure nodes. */ public enum OutlineNodeType { ROOT, CLASS, FUNCTION, FIELD, CSS_CLASS } private final OutlineNodeType type; private final JsonArray<OutlineNode> children; private final OutlineNode parent; private final int lineNumber; private final int column; private boolean enabled; private Anchor anchor; private String name; private TreeNodeElement<OutlineNode> renderedNode; public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @return The associated rendered {@link TreeNodeElement}. If there is no * tree node element rendered yet, then {@code null} is returned. */ public TreeNodeElement<OutlineNode> getRenderedTreeNode() { return renderedNode; } public OutlineNodeType getType() { return type; } public OutlineNode(String name, OutlineNodeType type, OutlineNode parent, int lineNumber, int column) { Preconditions.checkNotNull(type); this.parent = parent; this.lineNumber = lineNumber; this.column = column; this.name = name; this.type = type; this.children = JsonCollections.createArray(); } /** * 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 void setRenderedTreeNode(TreeNodeElement<OutlineNode> renderedNode) { this.renderedNode = renderedNode; } public JsonArray<OutlineNode> getChildren() { return children; } public OutlineNode getParent() { return parent; } @Override public int getLineNumber() { return lineNumber; } public int getColumn() { return column; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Anchor getAnchor() { return anchor; } public void setAnchor(Anchor anchor) { this.anchor = anchor; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/PyOutlineBuilder.java
client/src/main/java/com/google/collide/client/workspace/outline/PyOutlineBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import static com.google.collide.client.workspace.outline.OutlineNode.OUTLINE_NODE_ANCHOR_TYPE; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.CLASS; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.FUNCTION; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.ROOT; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_LINE_NUMBER; import com.google.collide.dto.CodeBlock; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; /** * Builder object that build node tree from given code block, and associates * nodes with lines in document. * * TODO: should we use autocompletion data? */ public class PyOutlineBuilder extends AbstractOutlineBuilder { @Override protected OutlineNode buildTree(CodeBlock source) { return buildTree(source, null); } @Override protected void maybeBindNode(OutlineNode node, Line line, AnchorManager anchorManager) { String text = line.getText(); String itemName = node.getName(); int nameColumn = text.indexOf(itemName, node.getColumn()); if (nameColumn >= 0) { node.setEnabled(true); Anchor anchor = anchorManager.createAnchor( OUTLINE_NODE_ANCHOR_TYPE, line, IGNORE_LINE_NUMBER, nameColumn); node.setAnchor(anchor); } } /** * Recursively builds node tree. * * <p>We assume that tree has the following structure: FILE that contains * FUNCTIONs and CLASSes that consist of FUNCTIONs. That way we always cut * the tree on FUNCTION nodes. */ private OutlineNode buildTree(CodeBlock block, OutlineNode parent) { OutlineNode.OutlineNodeType type; boolean isLeafNode = false; switch (block.getBlockType()) { case CodeBlock.Type.VALUE_FILE: type = ROOT; break; case CodeBlock.Type.VALUE_CLASS: type = CLASS; break; case CodeBlock.Type.VALUE_FUNCTION: isLeafNode = true; type = FUNCTION; break; default: return null; } OutlineNode result = new OutlineNode(block.getName(), type, parent, block.getStartLineNumber(), block.getStartColumn()); allNodes.add(result); // Can't or should not go deeper. if (isLeafNode || block.getChildren() == null) { return result; } JsonArray<OutlineNode> resultChildren = result.getChildren(); JsonArray<CodeBlock> blockChildren = block.getChildren(); final int size = blockChildren.size(); for (int i = 0; i < size; i++) { CodeBlock item = blockChildren.get(i); OutlineNode node = buildTree(item, result); if (node == null) { continue; } resultChildren.add(node); } return result; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineBuilder.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import com.google.collide.dto.CodeBlock; import com.google.collide.shared.document.Document; /** * Interface used to build language-specific outlines from code blocks. * */ public interface OutlineBuilder { /** * Build node tree and bind document lines. */ OutlineNode build(CodeBlock source, Document target); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineModel.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineModel.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import javax.annotation.Nullable; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Model object that holds essential navigation structure data data and sends * notifications when data is changed. */ public class OutlineModel { /** * OutlineModel notifications listener interface. */ public interface OutlineModelListener { public void rootChanged(OutlineNode newRoot); void nodeUpdated(OutlineNode node); void rootUpdated(); } private Document document; private OutlineModelListener listener; private OutlineNode root; public OutlineNode getRoot() { return root; } /** * Marks outdated nodes. */ public void setDisabled(final OutlineNode node) { if (node.isEnabled()) { node.setEnabled(false); listener.nodeUpdated(node); } } public void setListener(@Nullable OutlineModelListener listener) { this.listener = listener; } public void setRootChildren(JsonArray<OutlineNode> nodes) { JsonArray<OutlineNode> rootChildren = root.getChildren(); rootChildren.clear(); rootChildren.addAll(nodes); if (listener != null) { listener.rootUpdated(); } } public void updateRoot(OutlineNode root, Document document) { Preconditions.checkNotNull(root); Preconditions.checkNotNull(document); cleanup(); this.root = root; this.document = document; if (listener != null) { listener.rootChanged(root); } } public void cleanup() { if (root == null || document == null) { return; } JsonArray<Anchor> anchors = JsonCollections.createArray(); collectAttachedAnchors(anchors, root); AnchorManager anchorManager = document.getAnchorManager(); for (int i = 0, l = anchors.size(); i < l; i++) { anchorManager.removeAnchor(anchors.get(i)); } root = null; document = null; } private static void collectAttachedAnchors(JsonArray<Anchor> anchors, OutlineNode node) { Anchor anchor = node.getAnchor(); if (anchor != null && anchor.isAttached()) { anchors.add(anchor); } JsonArray<OutlineNode> children = node.getChildren(); if (children == null) { return; } for (int i = 0, l = children.size(); i < l; ++i) { collectAttachedAnchors(anchors, children.get(i)); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/JsOutlineBuilder.java
client/src/main/java/com/google/collide/client/workspace/outline/JsOutlineBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import static com.google.collide.client.workspace.outline.OutlineNode.OUTLINE_NODE_ANCHOR_TYPE; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.CLASS; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.FIELD; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.FUNCTION; import static com.google.collide.client.workspace.outline.OutlineNode.OutlineNodeType.ROOT; import static com.google.collide.shared.document.anchor.AnchorManager.IGNORE_LINE_NUMBER; import com.google.collide.dto.CodeBlock; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; /** * Builder object that build node tree from given code block, and associates * nodes with lines in document. * * TODO: should we use autocompletion data? * */ public class JsOutlineBuilder extends AbstractOutlineBuilder { static final String PROTOTYPE_NODE_NAME = "prototype"; @Override protected OutlineNode buildTree(CodeBlock source) { return buildTree(source, null, false); } @Override protected void maybeBindNode(OutlineNode node, Line line, AnchorManager anchorManager) { // TODO: Syntax allows line breaks -> examine several lines. String text = line.getText(); String itemName = node.getName(); int column = node.getColumn(); int nameColumn = text.indexOf(itemName, column); if (nameColumn < 0) { nameColumn = text.lastIndexOf(itemName); } if (nameColumn >= 0) { node.setEnabled(true); Anchor anchor = anchorManager.createAnchor( OUTLINE_NODE_ANCHOR_TYPE, line, IGNORE_LINE_NUMBER, nameColumn); node.setAnchor(anchor); } } /** * Recursively builds node tree. * * <p>There are 3 types of input blocks: FILE, FIELD and FUNCTION. * * <p>We classify this as different types of nodes:<ul> * <li> FILE is always a ROOT node * <li> FUNCTION is either CLASS node (if it contain other functions) * <li> or FUNCTION node (otherwise) * <li> FIELD block is classified as FIELD node only if they are * inside ROOT or CLASS node. * </ul> */ private OutlineNode buildTree(CodeBlock block, OutlineNode parent, boolean processFields) { OutlineNode.OutlineNodeType type; switch (block.getBlockType()) { case CodeBlock.Type.VALUE_FILE: type = ROOT; break; case CodeBlock.Type.VALUE_FIELD: if (!processFields) { return null; } type = FIELD; break; case CodeBlock.Type.VALUE_FUNCTION: type = FUNCTION; break; default: return null; } // Test if this block is CLASS. JsonArray<CodeBlock> blockChildren = block.getChildren(); if (blockChildren != null) { for (CodeBlock codeBlock : blockChildren.asIterable()) { if (codeBlock.getBlockType() == CodeBlock.Type.VALUE_FUNCTION) { type = CLASS; break; } else if (PROTOTYPE_NODE_NAME.equals(codeBlock.getName())) { type = CLASS; break; } } } OutlineNode result = new OutlineNode(block.getName(), type, parent, block.getStartLineNumber(), block.getStartColumn()); allNodes.add(result); addNodes(blockChildren, result, (type == ROOT) || (type == CLASS)); return result; } private void addNodes(JsonArray<CodeBlock> source, OutlineNode dest, boolean processFields) { if (source == null) { return; } JsonArray<OutlineNode> children = dest.getChildren(); for (CodeBlock item : source.asIterable()) { if (PROTOTYPE_NODE_NAME.equals(item.getName())) { addNodes(item.getChildren(), dest, processFields); } else { OutlineNode node = buildTree(item, dest, processFields); if (node == null) { continue; } children.add(node); } } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineNodeDataAdapter.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineNodeDataAdapter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import collide.client.treeview.NodeDataAdapter; import collide.client.treeview.TreeNodeElement; import com.google.collide.json.shared.JsonArray; /** * Adapter used by tree component to communicate with data class. */ public class OutlineNodeDataAdapter implements NodeDataAdapter<OutlineNode> { @Override public int compare(OutlineNode a, OutlineNode b) { // TODO: implement return 0; } @Override public boolean hasChildren(OutlineNode data) { JsonArray jsonArray = data.getChildren(); return jsonArray != null && !jsonArray.isEmpty(); } @Override public JsonArray<OutlineNode> getChildren(OutlineNode data) { return data.getChildren(); } @Override public String getNodeId(OutlineNode data) { return data.getName(); } @Override public String getNodeName(OutlineNode data) { return data.getName(); } @Override public OutlineNode getParent(OutlineNode data) { return data.getParent(); } @Override public TreeNodeElement<OutlineNode> getRenderedTreeNode(OutlineNode data) { return data.getRenderedTreeNode(); } @Override public void setNodeName(OutlineNode data, String name) { data.setName(name); } @Override public void setRenderedTreeNode(OutlineNode data, TreeNodeElement<OutlineNode> renderedNode) { data.setRenderedTreeNode(renderedNode); } @Override public OutlineNode getDragDropTarget(OutlineNode data) { return data; } @Override public JsonArray<String> getNodePath(OutlineNode data) { return NodeDataAdapter.PathUtils.getNodePath(this, data); } @Override public OutlineNode getNodeByPath(OutlineNode root, JsonArray<String> relativeNodePath) { // TODO: Not yet implemented. Also not used by the outline tree. return null; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineParser.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineParser.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; /** * Implementers build {@link OutlineNode}s from parsed Codemirror2 <code>Token</code>s. * */ public interface OutlineParser { /** * Performs cleanup. * * <p>After cleanup is invoked this instance should never be used again. */ void cleanup(); /** * Gets the root outline node. */ OutlineNode getRoot(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/workspace/outline/OutlineSection.java
client/src/main/java/com/google/collide/client/workspace/outline/OutlineSection.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.workspace.outline; import collide.client.treeview.Tree; import com.google.collide.client.AppContext; import com.google.collide.client.code.WorkspaceNavigationSection; import com.google.collide.client.workspace.outline.OutlineModel.OutlineModelListener; /** * Navigation panel that allows to quickly navigate through file structure. * */ public class OutlineSection extends WorkspaceNavigationSection<OutlineSection.View> { /** * Static factory method for obtaining an instance of the OutlineSection. */ public static OutlineSection create(View view, AppContext appContext, OutlineModel outlineModel, OutlineController outlineController) { // Create the Tree presenter. OutlineNodeRenderer nodeRenderer = new OutlineNodeRenderer(appContext.getResources()); OutlineNodeDataAdapter nodeDataAdapter = new OutlineNodeDataAdapter(); Tree<OutlineNode> tree = Tree.create(view.treeView, nodeDataAdapter, nodeRenderer, appContext.getResources()); tree.setTreeEventHandler(outlineController); // Instantiate and return the FileTreeSection. return new OutlineSection(view, tree, outlineModel); } private class OutlineModelListenerImpl implements OutlineModelListener { @Override public void rootChanged(OutlineNode newRoot) { tree.replaceSubtree(tree.getModel().getRoot(), newRoot, false); } @Override public void nodeUpdated(final OutlineNode node) { // TODO: we should have something like render(node) or even // adapter should be able to "update" rendered node. tree.renderTree(); } @Override public void rootUpdated() { tree.renderTree(); } } /** * CSS and images used by the OutlineSection. */ public interface Resources extends WorkspaceNavigationSection.Resources, Tree.Resources, OutlineNodeRenderer.Resources { } /** * View for the OutlineSection. */ public static class View extends WorkspaceNavigationSection.View<WorkspaceNavigationSection.ViewEvents> { final Tree.View<OutlineNode> treeView; public View(Resources res) { super(res); // Instantiate subviews. this.treeView = new Tree.View<OutlineNode>(res); // Initialize the View. setTitle("Code Navigator"); setStretch(true); setBlue(true); setContent(treeView.getElement()); setContentAreaScrollable(true); } } private final Tree<OutlineNode> tree; OutlineSection(View view, Tree<OutlineNode> tree, OutlineModel outlineModel) { super(view); this.tree = tree; outlineModel.setListener(new OutlineModelListenerImpl()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/Buffer.java
client/src/main/java/com/google/collide/client/editor/Buffer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import collide.client.common.CommonResources; import collide.client.common.Constants; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.document.linedimensions.LineDimensionsCalculator; import com.google.collide.client.document.linedimensions.LineDimensionsCalculator.RoundingStrategy; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.util.Executor; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.client.util.dom.DomUtils.Offset; import com.google.collide.client.util.dom.FontDimensionsCalculator.FontDimensions; 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.document.Document; import com.google.collide.shared.document.Document.LineCountListener; import com.google.collide.shared.document.Document.LineListener; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.ReadOnlyAnchor; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.ListenerRegistrar.RemoverManager; import com.google.collide.shared.util.TextUtils; import elemental.client.Browser; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; import elemental.events.EventRemover; import elemental.events.MouseEvent; import elemental.html.ClientRect; import elemental.html.DivElement; /* * TODO: Buffer has turned into an EditorSurface, but is still * called Buffer. */ /** * The presenter for the text portion of the editor. This class is used to * display text to the user, and to accept mouse input from the user. * * The lifecycle of this class is tied to the {@link Editor} that owns it. */ public class Buffer extends UiComponent<Buffer.View> implements LineListener, LineCountListener, CoordinateMap.DocumentSizeProvider { private static final int MARKER_COLUMN = 100; /** * Static factory method for obtaining an instance of Buffer. */ public static Buffer create(Buffer.Resources resources, FontDimensions fontDimensions, LineDimensionsCalculator lineDimensions, Executor renderTimeExecutor) { View view = new View(resources); Buffer buffer = new Buffer(view, fontDimensions, lineDimensions, renderTimeExecutor); MouseWheelRedirector.redirect(buffer, view.scrollableElement); return buffer; } /** * CssResource for the editor. */ public interface Css extends Editor.EditorSharedCss { String editorLineHeight(); String line(); String scrollbar(); int scrollableLeftPadding(); String spacer(); String textLayer(); String root(); String columnMarkerLine(); } /** * Listener that is notified of multiple click and drag mouse actions in the * text buffer area of the editor. */ public interface MouseDragListener { void onMouseClick(Buffer buffer, int clickCount, int x, int y, boolean isShiftHeld); void onMouseDrag(Buffer buffer, int x, int y); void onMouseDragRelease(Buffer buffer, int x, int y); } /* * TODO: listeners probably also want to be notified when the * mouse leaves the buffer */ /** * Listener that is notified of mouse movements in the buffer. * * <p>You probably want to use {@link MouseHoverManager} instead. * * TODO: Make it package-private. */ public interface MouseMoveListener { void onMouseMove(int x, int y); } /** * Listener that is notified of mouse movements out of the buffer. */ interface MouseOutListener { void onMouseOut(); } /** * Listener that is called when there is a click anywhere in the editor. */ public interface MouseClickListener { void onMouseClick(int x, int y); } /** * Listener that is called when the buffer's height changes. */ public interface HeightListener { void onHeightChanged(int height); } /** * ClientBundle for the editor. */ public interface Resources extends CommonResources.BaseResources { @Source({"Buffer.css", "constants.css", "collide/client/common/constants.css"}) Css workspaceEditorBufferCss(); } /** * Listener that is notified of scroll events. */ public interface ScrollListener { void onScroll(Buffer buffer, int scrollTop); } /** * Listener that is notified of window resize events.= */ public interface ResizeListener { void onResize(Buffer buffer, int documentHeight, int viewportHeight, int scrollTop); } /** * Listen for spacers being added or removed. */ public interface SpacerListener { void onSpacerAdded(Spacer spacer); void onSpacerHeightChanged(Spacer spacer, int oldHeight); void onSpacerRemoved(Spacer spacer, Line oldLine, int oldLineNumber); } /** * View for the buffer. */ public static class View extends CompositeView<ViewEvents> { private final Css css; private final EventListener mouseMoveListener = new EventListener() { @Override public void handleEvent(Event event) { int eventOffsetX = DomUtils.getOffsetX((MouseEvent) event); int eventOffsetY = DomUtils.getOffsetY((MouseEvent) event); Offset targetOffsetInBuffer = DomUtils.calculateElementOffset((Element) event.getTarget(), textLayerElement, true); getDelegate().onMouseMove( targetOffsetInBuffer.left + eventOffsetX, targetOffsetInBuffer.top + eventOffsetY); } }; private final EventListener mouseOutListener = new EventListener() { @Override public void handleEvent(Event evt) { /* * Check if we really should handle this event: * For mouseout, there are two situations: * 1. If relatedTarget is defined, then it (the DOM node to which the * mouse moves) should NOT be inside the buffer element itself. * 2. User leaves the window using a keyboard command or something else. * In this case, relatedTarget is undefined. */ com.google.gwt.user.client.Event gwtEvent = (com.google.gwt.user.client.Event) evt; Element relatedTarget = (Element) gwtEvent.getRelatedEventTarget(); if (relatedTarget == null || !scrollableElement.contains(relatedTarget)) { getDelegate().onMouseOut(); } } }; private EventRemover mouseMoveListenerRemover; private EventRemover mouseOutListenerRemover; private final Element rootElement; private final Element scrollbarElement; private final Element scrollableElement; private final Element textLayerElement; private final Element columnMarkerElement; private int scrollTopFromPreviousDispatch; private View(Resources res) { this.css = res.workspaceEditorBufferCss(); columnMarkerElement = Elements.createDivElement(css.columnMarkerLine()); textLayerElement = Elements.createDivElement(css.textLayer()); scrollableElement = createScrollableElement(res.baseCss()); scrollableElement.appendChild(textLayerElement); scrollbarElement = createScrollbarElement(res.baseCss()); rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(scrollableElement); rootElement.appendChild(scrollbarElement); setElement(rootElement); } private Element createScrollbarElement(CommonResources.BaseCss baseCss) { final DivElement scrollbarElement = Elements.createDivElement(css.scrollbar()); scrollbarElement.addClassName(baseCss.documentScrollable()); scrollbarElement.addEventListener(Event.SCROLL, new EventListener() { @Override public void handleEvent(Event evt) { setScrollTop(scrollbarElement.getScrollTop(), false); } }, false); // Prevent stealing focus from scrollable. scrollbarElement.addEventListener(Event.MOUSEDOWN, new EventListener() { @Override public void handleEvent(Event evt) { evt.preventDefault(); } }, false); // Empty child will be set to the document height scrollbarElement.appendChild(Elements.createDivElement()); return scrollbarElement; } private Element createScrollableElement(CommonResources.BaseCss baseCss) { final DivElement scrollableElement = Elements.createDivElement(css.scrollable()); scrollableElement.addClassName(baseCss.documentScrollable()); scrollableElement.addEventListener(Event.SCROLL, new EventListener() { @Override public void handleEvent(Event evt) { setScrollTop(scrollableElement.getScrollTop(), false); } }, false); scrollableElement.addEventListener(Event.CONTEXTMENU, new EventListener() { @Override public void handleEvent(Event evt) { /* * TODO: eventually have our context menu, but for now * disallow browser's since it's confusing that it does not have copy * nor paste options */ evt.stopPropagation(); evt.preventDefault(); } }, false); // TODO: Detach listener in appropriate moment. MouseGestureListener.createAndAttach(scrollableElement, new MouseGestureListener.Callback() { @Override public boolean onClick(int clickCount, MouseEvent event) { // The buffer area does not include the scrollable's padding int bufferClientLeft = css.scrollableLeftPadding(); int bufferClientTop = 0; for (Element element = scrollableElement; element.getOffsetParent() != null; element = element.getOffsetParent()) { bufferClientLeft += element.getOffsetLeft(); bufferClientTop += element.getOffsetTop(); } /* * This onClick method will get called for horizontal scrollbar interactions. We want to * exit early for those. It will not get called for vertical scrollbar interactions since * that is a separate element outside of the scrollable element. */ if (scrollableElement == event.getTarget()) { // Test if the mouse event is on the horizontal scrollbar. int relativeY = event.getClientY() - bufferClientTop; if (relativeY > scrollableElement.getClientHeight()) { // Prevent editor losing focus event.preventDefault(); return false; } } getDelegate().onMouseClick(clickCount, event.getClientX(), event.getClientY(), bufferClientLeft, bufferClientTop, event.isShiftKey()); return true; } @Override public void onDragRelease(MouseEvent event) { getDelegate().onMouseDragRelease(event.getClientX(), event.getClientY()); } @Override public void onDrag(MouseEvent event) { getDelegate().onMouseDrag(event.getClientX(), event.getClientY()); } }); /* * Don't allow tabbing to this -- the input element will be tabbable * instead */ scrollableElement.setTabIndex(-1); Browser.getWindow().addEventListener(Event.RESIZE, new EventListener() { @Override public void handleEvent(Event evt) { // TODO: also listen for the navigation slider // this event is being caught multiple times, and sometimes the // calculated values are all zero. So only respond if we have positive // values. int height = (int) textLayerElement.getBoundingClientRect().getHeight(); int viewportHeight = getHeight(); if (height > 0 && viewportHeight > 0) { getDelegate().onScrollableResize( height, viewportHeight, scrollableElement.getScrollTop()); } } }, false); return scrollableElement; } public int getScrollLeft() { return scrollableElement.getScrollLeft(); } private void addLine(Element lineElement) { String className = lineElement.getClassName(); if (className == null || className.isEmpty()) { lineElement.addClassName(css.line()); } textLayerElement.appendChild(lineElement); } private Element getFirstLine() { return textLayerElement.getFirstChildElement(); } private int getHeight() { return scrollableElement.getClientHeight(); } private int getScrollTop() { return scrollableElement.getScrollTop(); } private int getScrollHeight() { return scrollableElement.getScrollHeight(); } private int getWidth() { return scrollableElement.getClientWidth(); } private void reset() { scrollableElement.setScrollTop(0); scrollTopFromPreviousDispatch = 0; textLayerElement.setInnerHTML(""); } private void setBufferHeight(int height) { textLayerElement.getStyle().setHeight(height, CSSStyleDeclaration.Unit.PX); columnMarkerElement.getStyle().setHeight(height, CSSStyleDeclaration.Unit.PX); /* * For expediency, we deviate from typical scrollbar behavior by having * the vertical scrollbar span the entire height, even in the presence of * a horizontal scrollbar in the scrollable element. The problem is that * if the scrollable element is scrolled all the way to its bottom, its * scrolltop will be SCROLLBAR_SIZE greater than what the * scrollbarElement's scrolltop is when scrollbarElement's scrolled all * the way to the bottom (because scrollTop + clientHeight cannot be * greater than scrollHeight). We get around this problem by adding the * SCROLLBAR_SIZE to the scrollbar element's height, which allows the * scrollTops on both elements to be the same. (There's now a little room * at the bottom of the vertical scrollbar that won't scroll the * scrollable element, but that's OK.) */ scrollbarElement.getFirstChildElement().getStyle() .setHeight(height + Constants.SCROLLBAR_SIZE, CSSStyleDeclaration.Unit.PX); } public void setWidth(int width) { textLayerElement.getStyle().setWidth(width, CSSStyleDeclaration.Unit.PX); } private void setScrollTop(int scrollTop, boolean forceDispatch) { if (scrollTop != scrollableElement.getScrollTop()) { scrollableElement.setScrollTop(scrollTop); } if (scrollTop != scrollbarElement.getScrollTop()) { scrollbarElement.setScrollTop(scrollTop); } if (scrollTop != scrollTopFromPreviousDispatch) { // Use getScrollTop in case the desired scrollTop could not be set int newScrollTop = scrollableElement.getScrollTop(); getDelegate().onScroll(newScrollTop); scrollTopFromPreviousDispatch = newScrollTop; } } public void setScrollLeft(int scrollLeft) { scrollableElement.setScrollLeft(scrollLeft); } void registerMouseMoveListener() { if (mouseMoveListenerRemover == null) { mouseMoveListenerRemover = scrollableElement.addEventListener(Event.MOUSEMOVE, mouseMoveListener, false); } } void unregisterMouseMoveListener() { if (mouseMoveListenerRemover != null) { mouseMoveListenerRemover.remove(); mouseMoveListenerRemover = null; } } void registerMouseOutListener() { if (mouseOutListenerRemover == null) { mouseOutListenerRemover = scrollableElement.addEventListener(Event.MOUSEOUT, mouseOutListener, false); } } void unregisterMouseOutListener() { if (mouseOutListenerRemover != null) { mouseOutListenerRemover.remove(); mouseOutListenerRemover = null; } } } private interface ViewEvents { void onMouseClick(int clickCount, int clientX, int clientY, int bufferClientLeft, int bufferClientTop, boolean isShiftHeld); void onMouseDrag(int clientX, int clientY); void onMouseDragRelease(int clientX, int clientY); void onMouseMove(int bufferX, int bufferY); void onMouseOut(); void onScroll(int scrollTop); void onScrollableResize(int height, int viewportHeight, int scrollTop); } private final CoordinateMap coordinateMap; private final ElementManager elementManager; private final ListenerManager<HeightListener> heightListenerManager = ListenerManager.create(); private int maxLineLength; private final ListenerManager<MouseClickListener> mouseClickListenerManager = ListenerManager.create(); private final ListenerManager<MouseDragListener> mouseDragListenerManager = ListenerManager.create(); private final ListenerManager<MouseMoveListener> mouseMoveListenerManager = ListenerManager.create(new ListenerManager.RegistrationListener<MouseMoveListener>() { @Override public void onListenerAdded(MouseMoveListener listener) { if (mouseMoveListenerManager.getCount() == 1) { getView().registerMouseMoveListener(); } } @Override public void onListenerRemoved(MouseMoveListener listener) { if (mouseMoveListenerManager.getCount() == 0) { getView().unregisterMouseMoveListener(); } } }); private final ListenerManager<MouseOutListener> mouseOutListenerManager = ListenerManager.create(new ListenerManager.RegistrationListener<MouseOutListener>() { @Override public void onListenerAdded(MouseOutListener listener) { if (mouseOutListenerManager.getCount() == 1) { getView().registerMouseOutListener(); } } @Override public void onListenerRemoved(MouseOutListener listener) { if (mouseOutListenerManager.getCount() == 0) { getView().unregisterMouseOutListener(); } } }); private static final Dispatcher<MouseOutListener> mouseOutListenerDispatcher = new Dispatcher<MouseOutListener>() { @Override public void dispatch(MouseOutListener listener) { listener.onMouseOut(); } }; private final ListenerManager<SpacerListener> spacerListenerManager = ListenerManager.create(); private Document document; private final int editorLineHeight; private final ListenerManager<ScrollListener> scrollListenerManager = ListenerManager.create(); private final ListenerManager<ResizeListener> resizeListenerManager = ListenerManager.create(); private final FontDimensions fontDimensions; private final LineDimensionsCalculator lineDimensions; private final RemoverManager documentChangedRemoverManager = new RemoverManager(); private final Executor renderTimeExecutor; private Buffer(View view, FontDimensions fontDimensions, LineDimensionsCalculator lineDimensions, Executor renderTimeExecutor) { super(view); this.fontDimensions = fontDimensions; this.lineDimensions = lineDimensions; this.renderTimeExecutor = renderTimeExecutor; this.editorLineHeight = CssUtils.parsePixels(view.css.editorLineHeight()); coordinateMap = new CoordinateMap(this); elementManager = new ElementManager(getView().textLayerElement, this); updateColumnMarkerPosition(); view.setDelegate(new ViewEvents() { private int bufferLeft; private int bufferTop; private int bufferRelativeX; private int bufferRelativeY; @Override public void onMouseClick(final int clickCount, int clientX, int clientY, int bufferClientLeft, int bufferClientTop, final boolean isShiftHeld) { this.bufferLeft = bufferClientLeft; this.bufferTop = bufferClientTop; updateBufferRelativeXy(clientX, clientY); if (clickCount == 1) { // Dispatch to simple click listeners mouseClickListenerManager.dispatch(new Dispatcher<MouseClickListener>() { @Override public void dispatch(MouseClickListener listener) { listener.onMouseClick(bufferRelativeX, bufferRelativeY); } }); } mouseDragListenerManager.dispatch(new Dispatcher<MouseDragListener>() { @Override public void dispatch(MouseDragListener listener) { listener.onMouseClick( Buffer.this, clickCount, bufferRelativeX, bufferRelativeY, isShiftHeld); } }); } @Override public void onMouseDrag(final int clientX, final int clientY) { updateBufferRelativeXy(clientX, clientY); mouseDragListenerManager.dispatch(new Dispatcher<MouseDragListener>() { @Override public void dispatch(MouseDragListener listener) { listener.onMouseDrag(Buffer.this, bufferRelativeX, bufferRelativeY); } }); } @Override public void onMouseDragRelease(final int clientX, final int clientY) { updateBufferRelativeXy(clientX, clientY); mouseDragListenerManager.dispatch(new Dispatcher<MouseDragListener>() { @Override public void dispatch(MouseDragListener listener) { listener.onMouseDragRelease(Buffer.this, bufferRelativeX, bufferRelativeY); } }); } @Override public void onMouseMove(final int bufferX, final int bufferY) { mouseMoveListenerManager.dispatch(new Dispatcher<MouseMoveListener>() { @Override public void dispatch(MouseMoveListener listener) { listener.onMouseMove(bufferX, bufferY); } }); } @Override public void onMouseOut() { mouseOutListenerManager.dispatch(mouseOutListenerDispatcher); } private void updateBufferRelativeXy(int clientX, int clientY) { /* * TODO: consider moving this element top/left-relative * code to MouseGestureListener */ bufferRelativeX = clientX - bufferLeft + getScrollLeft(); bufferRelativeY = clientY - bufferTop + getScrollTop(); } @Override public void onScroll(final int scrollTop) { scrollListenerManager.dispatch(new Dispatcher<ScrollListener>() { @Override public void dispatch(ScrollListener listener) { listener.onScroll(Buffer.this, scrollTop); } }); } @Override public void onScrollableResize( final int height, final int viewportHeight, final int scrollTop) { // TODO: Look into why this is necessary. updateTextWidth(); updateVerticalScrollbarDisplayVisibility(); updateColumnMarkerHeight(); resizeListenerManager.dispatch(new Dispatcher<ResizeListener>() { @Override public void dispatch(ResizeListener listener) { listener.onResize(Buffer.this, height, viewportHeight, scrollTop); } }); } }); } public void addLineElement(Element lineElement) { getView().addLine(lineElement); } public boolean hasLineElement(Element lineElement) { return lineElement.getParentElement() != null; } /* * TODO: consider making ElementManager public, and a * getElementManager() method instead */ public void addAnchoredElement(ReadOnlyAnchor anchor, Element element) { elementManager.addAnchoredElement(anchor, element); } public void removeAnchoredElement(ReadOnlyAnchor anchor, Element element) { elementManager.removeAnchoredElement(anchor, element); } public void addUnmanagedElement(Element element) { elementManager.addUnmanagedElement(element); } public void removeUnmanagedElement(Element element) { elementManager.removeUnmanagedElement(element); } /** * Returns a newly added spacer above the given {@code lineInfo} with the * given {@code height}. */ public Spacer addSpacer(LineInfo lineInfo, int height) { final Spacer createdSpacer = coordinateMap.createSpacer(lineInfo, height, this, getView().css.spacer()); updateBufferHeightAndMaybeScrollTop(calculateSpacerTop(createdSpacer), height); spacerListenerManager.dispatch(new Dispatcher<Buffer.SpacerListener>() { @Override public void dispatch(SpacerListener listener) { listener.onSpacerAdded(createdSpacer); } }); return createdSpacer; } public void removeSpacer(final Spacer spacer) { final Line spacerLine = spacer.getLine(); final int spacerLineNumber = spacer.getLineNumber(); if (coordinateMap.removeSpacer(spacer)) { updateBufferHeightAndMaybeScrollTop(convertLineNumberToY(spacerLineNumber), -spacer.getHeight()); spacerListenerManager.dispatch(new Dispatcher<Buffer.SpacerListener>() { @Override public void dispatch(SpacerListener listener) { listener.onSpacerRemoved(spacer, spacerLine, spacerLineNumber); } }); } } public boolean hasSpacers() { return coordinateMap.getTotalSpacerHeight() != 0; } @Override public void handleSpacerHeightChanged(final Spacer spacer, final int oldHeight) { int deltaHeight = spacer.getHeight() - oldHeight; updateBufferHeightAndMaybeScrollTop(calculateSpacerTop(spacer), deltaHeight); spacerListenerManager.dispatch(new Dispatcher<Buffer.SpacerListener>() { @Override public void dispatch(SpacerListener listener) { listener.onSpacerHeightChanged(spacer, oldHeight); } }); } public int calculateSpacerTop(Spacer spacer) { return coordinateMap.convertLineNumberToY(spacer.getLineNumber()) - spacer.getHeight(); } /** * @param inDocumentRange whether to do a validation check on the return line * number to ensure it is in the document's range */ public int convertYToLineNumber(int y, boolean inDocumentRange) { int lineNumber = coordinateMap.convertYToLineNumber(y); return inDocumentRange ? LineUtils.getValidLineNumber(lineNumber, document) : lineNumber; } public int convertXToRoundedVisibleColumn(int x, Line line) { int roundedColumn = convertXToColumn(x, line, RoundingStrategy.ROUND); return TextUtils.findNextCharacterInclusive(line.getText(), roundedColumn); } public int convertXToColumn(int x, Line line, RoundingStrategy roundingStrategy) { return LineUtils.rubberbandColumn( line, lineDimensions.convertXToColumn(line, x, roundingStrategy)); } public ListenerRegistrar<HeightListener> getHeightListenerRegistrar() { return heightListenerManager; } /** * Returns the top for a line, e.g. if {@code lineNumber} is 0 and it is a * simple document, 0 will be returned. */ public int convertLineNumberToY(int lineNumber) { return coordinateMap.convertLineNumberToY(lineNumber); } public int convertColumnToX(Line line, int column) { return (int) Math.floor(lineDimensions.convertColumnToX(line, column)); } public int calculateColumnLeftRelativeToScrollableIgnoringSpecialCharacters(int column) { return calculateColumnLeftIgnoringSpecialCharacters(column) + getView().css.scrollableLeftPadding(); } /** * Converts a column to an x value assuming all characters in-between are * number width. * <p> * DO NOT USE THIS UNLESS IT IS INTENTIONAL AND YOU UNDERSTAND THE * CONSEQUENCES. DO NOT USE IT JUST BECAUSE IT DOES NOT REQUIRE A * {@link Line}. */ public int calculateColumnLeftIgnoringSpecialCharacters(int column) { return (int) Math.floor(fontDimensions.getCharacterWidth() * column); } public int calculateColumnLeft(Line line, int column) { return Math.max(0, convertColumnToX(line, column)); } public int calculateLineBottom(int lineNumber) { return convertLineNumberToY(lineNumber) + editorLineHeight; } public int calculateLineTop(int lineNumber) { return convertLineNumberToY(lineNumber); } public ListenerRegistrar<MouseClickListener> getMouseClickListenerRegistrar() { return mouseClickListenerManager; } public ListenerRegistrar<SpacerListener> getSpacerListenerRegistrar() { return spacerListenerManager; } public Document getDocument() { return document; } @Override public float getEditorCharacterWidth() { return fontDimensions.getCharacterWidth(); } /** * TODO: So right now this uses a constant, unfortunately it's not * accurate when zoomed in/out and sometimes leads to whitespace between * selection lines. This should be converted to fontDimensions.getHeight(). */ @Override public int getEditorLineHeight() { return editorLineHeight; } public Element getFirstLineElement() { return getView().getFirstLine(); } public int getFlooredHeightInLines() { /* * Imagine scrollTop = 0, lineHeight = 10, and height = 20. If we passed * "true", convertYToLineNumber(0+20) would bound on the document size and * return 1 instead of the 2 that we need. */ return convertYToLineNumber(getScrollTop() + getHeight(), false) - convertYToLineNumber(getScrollTop(), false); } public int getHeight() { return getView().getHeight(); } public ListenerRegistrar<MouseDragListener> getMouseDragListenerRegistrar() { return mouseDragListenerManager; } // TODO: Make it package-private. public ListenerRegistrar<MouseMoveListener> getMouseMoveListenerRegistrar() { return mouseMoveListenerManager; } ListenerRegistrar<MouseOutListener> getMouseOutListenerRegistrar() { return mouseOutListenerManager; } public int getMaxLineLength() { return maxLineLength; } public int getScrollLeft() { return getView().getScrollLeft(); } public ListenerRegistrar<ScrollListener> getScrollListenerRegistrar() { return scrollListenerManager; } public ListenerRegistrar<ResizeListener> getResizeListenerRegistrar() { return resizeListenerManager; } public int getScrollTop() { return getView().getScrollTop(); } public int getScrollHeight() { return getView().getScrollHeight(); } public int getWidth() { return getView().getWidth(); } public void handleDocumentChanged(Document newDocument) { documentChangedRemoverManager.remove(); document = newDocument; coordinateMap.handleDocumentChange(newDocument); lineDimensions.handleDocumentChange(newDocument); getView().reset(); documentChangedRemoverManager.track(newDocument.getLineListenerRegistrar().add(this)); updateBufferHeight(); } @Override public void onLineAdded(Document document, final int lineNumber, final JsonArray<Line> addedLines) { renderTimeExecutor.execute(new Runnable() { @Override public void run() { updateBufferHeightAndMaybeScrollTop(convertLineNumberToY(lineNumber), addedLines.size() * getEditorLineHeight()); } }); } @Override public void onLineRemoved(final Document document, final int lineNumber, final JsonArray<Line> removedLines) { renderTimeExecutor.execute(new Runnable() { @Override public void run() { /* * Since the removed line(s) no longer exist, we need to make sure to * clamp them */ int safeLineNumber = Math.min(document.getLastLineNumber(), lineNumber);
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/com/google/collide/client/editor/Editor.java
client/src/main/java/com/google/collide/client/editor/Editor.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import org.waveprotocol.wave.client.common.util.SignalEvent; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.code.parenmatch.ParenMatchHighlighter; import com.google.collide.client.document.linedimensions.LineDimensionsCalculator; import com.google.collide.client.editor.gutter.Gutter; import com.google.collide.client.editor.gutter.LeftGutterManager; import com.google.collide.client.editor.input.InputController; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.client.editor.renderer.RenderTimeExecutor; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.editor.search.SearchMatchRenderer; import com.google.collide.client.editor.search.SearchModel; import com.google.collide.client.editor.selection.CursorView; import com.google.collide.client.editor.selection.LocalCursorController; import com.google.collide.client.editor.selection.SelectionLineRenderer; import com.google.collide.client.editor.selection.SelectionManager; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.dom.FontDimensionsCalculator; import com.google.collide.client.util.dom.FontDimensionsCalculator.FontDimensions; import com.google.collide.json.shared.JsonArray; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import elemental.dom.Element; import elemental.events.Event; /** * The presenter for the Collide editor. * * This class composes many of the other classes that together form the editor. * For example, the area where the text is displayed, the {@link Buffer}, is a * nested presenter. Other components are not presenters, such as the input * mechanism which is handled by the {@link InputController}. * * If an added element wants native browser selection, you must not inherit the * "user-select" CSS property. See * {@link CssUtils#setUserSelect(Element, boolean)}. */ public class Editor extends UiComponent<Editor.View> { /** * Static factory method for obtaining an instance of the Editor. */ public static Editor create(EditorContext<?> editorContext) { FontDimensionsCalculator fontDimensionsCalculator = FontDimensionsCalculator.get(editorContext.getResources().workspaceEditorCss().editorFont()); RenderTimeExecutor renderTimeExecutor = new RenderTimeExecutor(); LineDimensionsCalculator lineDimensions = LineDimensionsCalculator.create(fontDimensionsCalculator); Buffer buffer = Buffer.create(editorContext.getResources(), fontDimensionsCalculator.getFontDimensions(), lineDimensions, renderTimeExecutor); InputController input = new InputController(); View view = new View(editorContext.getResources(), buffer.getView().getElement(), input.getInputElement()); FocusManager focusManager = new FocusManager(buffer, input.getInputElement()); return new Editor(editorContext, view, buffer, input, focusManager, fontDimensionsCalculator, renderTimeExecutor); } /** * Animation CSS. */ @CssResource.Shared public interface EditorSharedCss extends CssResource { String animationEnabled(); String scrollable(); } /** * CssResource for the editor. */ public interface Css extends EditorSharedCss { String leftGutter(); String editorFont(); String root(); String scrolled(); String gutter(); String lineRendererError(); } /** * A listener that is called when the user presses a key. */ public interface KeyListener { /* * The reason for preventDefault() not preventing default behavior is that * Firefox does not have support the defaultPrevented attribute, so we have * know way of knowing if it was prevented from the native event. We could * create a proxy for SignalEvent to note calls to preventDefault(), but * this would not catch the case that the implementor interacts directly to * the native event. */ /** * @param event the event for the key press. Note: Calling preventDefault() * may not prevent the default behavior in some cases. The return * value of this method is a better channel for indicating the * default behavior should be prevented. * @return true if the event was handled (the default behavior will not run * in this case), false to proceed with the default behavior. Even * if true is returned, other listeners will still get the callback */ boolean onKeyPress(SignalEvent event); } /** * A listener that is called on "keyup" native event. */ public interface NativeKeyUpListener { /** * @param event the event for the key up * @return true if the event was handled, false to proceed with default * behavior */ boolean onNativeKeyUp(Event event); } /** * ClientBundle for the editor. */ public interface Resources extends Buffer.Resources, CursorView.Resources, SelectionLineRenderer.Resources, SearchMatchRenderer.Resources, ParenMatchHighlighter.Resources { @Source({"Editor.css", "constants.css"}) Css workspaceEditorCss(); @Source("squiggle.gif") ImageResource squiggle(); } /** * A listener that is called after the user enters or deletes text and before * it is applied to the document. */ public interface BeforeTextListener { /** * Note: You should not mutate the document within this callback, as this is * not supported yet and can lead to other clients having stale position * information inside the {@code textChange}. * * Note: The {@link TextChange} contains a reference to the live * {@link Line} from the document model. If you hold on to a reference after * {@link #onBeforeTextChange} returns, beware that the contents of the * {@link Line} could change, invalidating some of the state in the * {@link TextChange}. * * @param textChange the text change whose last line will be the same as the * insertion point (since the text hasn't been inserted yet) */ void onBeforeTextChange(TextChange textChange); } /** * A listener that is called when the user enters or deletes text. * * Similar to {@link Document.TextListener} except is only called when the * text is entered/deleted by the local user. */ public interface TextListener { /** * Note: You should not mutate the document within this callback, as this is * not supported yet and can lead to other clients having stale position * information inside the {@code textChange}. * * Note: The {@link TextChange} contains a reference to the live * {@link Line} from the document model. If you hold on to a reference after * {@link #onTextChange} returns, beware that the contents of the * {@link Line} could change, invalidating some of the state in the * {@link TextChange}. */ void onTextChange(TextChange textChange); } /** * A listener that is called when the document changes. * * This can be used by external clients of the editor; if the client is a * component of the editor, use {@link Editor#setDocument(Document)} instead. */ public interface DocumentListener { void onDocumentChanged(Document oldDocument, Document newDocument); } /** * A listener that is called when the editor becomes or is no longer * read-only. */ public interface ReadOnlyListener { void onReadOnlyChanged(boolean isReadOnly); } /** * The view for the editor, containing gutters and the buffer. This exposes * only the ability to enable or disable animations. */ public static class View extends CompositeView<Void> { private final Element bufferElement; final Css css; final Resources res; private View(Resources res, Element bufferElement, Element inputElement) { this.res = res; this.bufferElement = bufferElement; this.css = res.workspaceEditorCss(); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(bufferElement); rootElement.appendChild(inputElement); setElement(rootElement); } private void addGutter(Element gutterElement) { getElement().insertBefore(gutterElement, bufferElement); } private void removeGutter(Element gutterElement) { getElement().removeChild(gutterElement); } public void setAnimationEnabled(boolean enabled) { // TODO: Re-enable animations when they are stable. if (enabled) { // getElement().addClassName(css.animationEnabled()); } else { // getElement().removeClassName(css.animationEnabled()); } } public Resources getResources() { return res; } } public static final int ANIMATION_DURATION = 100; private static int idCounter = 0; private final EditorContext<?> editorContext; private final Buffer buffer; private Document document; private final ListenerManager<DocumentListener> documentListenerManager = ListenerManager.create(); private final EditorDocumentMutator editorDocumentMutator; private final FontDimensionsCalculator editorFontDimensionsCalculator; private EditorUndoManager editorUndoManager; private final FocusManager focusManager; private final MouseHoverManager mouseHoverManager; private final int id = idCounter++; private final FontDimensionsCalculator.Callback fontDimensionsChangedCallback = new FontDimensionsCalculator.Callback() { @Override public void onFontDimensionsChanged(FontDimensions fontDimensions) { handleFontDimensionsChanged(); } }; private final JsonArray<Gutter> gutters = JsonCollections.createArray(); private final InputController input; private final LeftGutterManager leftGutterManager; private LocalCursorController localCursorController; private final ListenerManager<ReadOnlyListener> readOnlyListenerManager = ListenerManager .create(); private Renderer renderer; private SearchModel searchModel; private SelectionManager selectionManager; private final EditorActivityManager editorActivityManager; private ViewportModel viewport; private boolean isReadOnly; private final RenderTimeExecutor renderTimeExecutor; private Editor(EditorContext<?> editorContext, View view, Buffer buffer, InputController input, FocusManager focusManager, FontDimensionsCalculator editorFontDimensionsCalculator, RenderTimeExecutor renderTimeExecutor) { super(view); this.editorContext = editorContext; this.buffer = buffer; this.input = input; this.focusManager = focusManager; this.editorFontDimensionsCalculator = editorFontDimensionsCalculator; this.renderTimeExecutor = renderTimeExecutor; Gutter leftGutter = createGutter( false, Gutter.Position.LEFT, editorContext.getResources().workspaceEditorCss().leftGutter()); leftGutterManager = new LeftGutterManager(leftGutter, buffer); editorDocumentMutator = new EditorDocumentMutator(this); mouseHoverManager = new MouseHoverManager(this); editorActivityManager = new EditorActivityManager(editorContext.getUserActivityManager(), buffer.getScrollListenerRegistrar(), getKeyListenerRegistrar()); // TODO: instantiate input from here input.initializeFromEditor(this, editorDocumentMutator); setAnimationEnabled(true); addBoxShadowOnScrollHandler(); editorFontDimensionsCalculator.addCallback(fontDimensionsChangedCallback); } private void handleFontDimensionsChanged() { buffer.repositionAnchoredElementsWithColumn(); if (renderer != null) { /* * TODO: think about a scheme where we don't have to rerender * the whole viewport (currently we do because of the right-side gap * fillers) */ renderer.renderAll(); } } /** * Adds a scroll handler to the buffer scrollableElement so that a drop shadow * can be added and removed when scrolled. */ private void addBoxShadowOnScrollHandler() { } public void addLineRenderer(LineRenderer lineRenderer) { /* * TODO: Because the line renderer is document-scoped, line * renderers have to re-add themselves whenever the document changes. This * is unexpected. */ renderer.addLineRenderer(lineRenderer); } public Gutter createGutter(boolean overviewMode, Gutter.Position position, String cssClassName) { Gutter gutter = Gutter.create(overviewMode, position, cssClassName, buffer); if (viewport != null && renderer != null) { gutter.handleDocumentChanged(viewport, renderer); } gutters.add(gutter); gutter.getGutterElement().addClassName(getView().css.gutter()); getView().addGutter(gutter.getGutterElement()); return gutter; } public void removeGutter(Gutter gutter) { getView().removeGutter(gutter.getGutterElement()); gutters.remove(gutter); } public void setAnimationEnabled(boolean enabled) { getView().setAnimationEnabled(enabled); } public ListenerRegistrar<BeforeTextListener> getBeforeTextListenerRegistrar() { return editorDocumentMutator.getBeforeTextListenerRegistrar(); } public Buffer getBuffer() { return buffer; } /* * TODO: if left gutter manager gets public API, expose that * instead of directly exposign the gutter. Or, if we don't want to expose * Gutter#setWidth publicly for the left gutter, make LeftGutterManager the * public API. */ public Gutter getLeftGutter() { return leftGutterManager.getGutter(); } public Document getDocument() { return document; } /** * Returns a document mutator that will also notify editor text listeners. */ public EditorDocumentMutator getEditorDocumentMutator() { return editorDocumentMutator; } public Element getElement() { return getView().getElement(); } public FocusManager getFocusManager() { return focusManager; } public MouseHoverManager getMouseHoverManager() { return mouseHoverManager; } public ListenerRegistrar<KeyListener> getKeyListenerRegistrar() { return input.getKeyListenerRegistrar(); } public ListenerRegistrar<NativeKeyUpListener> getNativeKeyUpListenerRegistrar() { return input.getNativeKeyUpListenerRegistrar(); } public Renderer getRenderer() { return renderer; } public SearchModel getSearchModel() { return searchModel; } public SelectionModel getSelection() { return selectionManager.getSelectionModel(); } public LocalCursorController getCursorController() { return localCursorController; } public ListenerRegistrar<TextListener> getTextListenerRegistrar() { return editorDocumentMutator.getTextListenerRegistrar(); } public ListenerRegistrar<DocumentListener> getDocumentListenerRegistrar() { return documentListenerManager; } // TODO: need a public interface and impl public ViewportModel getViewport() { return viewport; } public boolean isMutatingDocumentFromUndoOrRedo() { return editorUndoManager.isMutatingDocument(); } public void removeLineRenderer(LineRenderer lineRenderer) { renderer.removeLineRenderer(lineRenderer); } public void setDocument(final Document document) { final Document oldDocument = this.document; if (oldDocument != null) { // Teardown the objects depending on the old document renderer.teardown(); viewport.teardown(); selectionManager.teardown(); localCursorController.teardown(); editorUndoManager.teardown(); searchModel.teardown(); } this.document = document; /* * TODO: dig into each component, figure out dependencies, * break apart components so we can reduce circular dependencies which * require the multiple stages of initialization */ // Core editor components buffer.handleDocumentChanged(document); leftGutterManager.handleDocumentChanged(document); selectionManager = SelectionManager.create(document, buffer, focusManager, editorContext.getResources()); SelectionModel selection = selectionManager.getSelectionModel(); viewport = ViewportModel.create(document, selection, buffer); input.handleDocumentChanged(document, selection, viewport); renderer = Renderer.create(document, viewport, buffer, getLeftGutter(), selection, focusManager, this, editorContext.getResources(), renderTimeExecutor); // Delayed core editor component initialization viewport.initialize(); selection.initialize(viewport); selectionManager.initialize(renderer); buffer.handleComponentsInitialized(viewport, renderer); for (int i = 0, n = gutters.size(); i < n; i++) { gutters.get(i).handleDocumentChanged(viewport, renderer); } // Non-core editor components editorUndoManager = EditorUndoManager.create(this, document, selection); searchModel = SearchModel.create(editorContext, document, renderer, viewport, selection, editorDocumentMutator); localCursorController = LocalCursorController.create(editorContext.getResources(), focusManager, selection, buffer, this); documentListenerManager.dispatch(new Dispatcher<Editor.DocumentListener>() { @Override public void dispatch(DocumentListener listener) { listener.onDocumentChanged(oldDocument, document); } }); } public void undo() { editorUndoManager.undo(); } public void redo() { editorUndoManager.redo(); } public void scrollTo(int lineNumber, int column) { if (document != null) { LineInfo lineInfo = document.getLineFinder().findLine(lineNumber); /* * TODO: the cursor will be the last line in the viewport, * fix this */ SelectionModel selectionModel = getSelection(); selectionModel.deselect(); selectionModel.setCursorPosition(lineInfo, column); } } public void cleanup() { editorFontDimensionsCalculator.removeCallback(fontDimensionsChangedCallback); editorActivityManager.teardown(); } public void setReadOnly(final boolean isReadOnly) { if (this.isReadOnly == isReadOnly) { return; } this.isReadOnly = isReadOnly; readOnlyListenerManager.dispatch(new Dispatcher<Editor.ReadOnlyListener>() { @Override public void dispatch(ReadOnlyListener listener) { listener.onReadOnlyChanged(isReadOnly); } }); } public boolean isReadOnly() { return isReadOnly; } public ListenerRegistrar<ReadOnlyListener> getReadOnlyListenerRegistrar() { return readOnlyListenerManager; } public int getId() { return id; } @VisibleForTesting public InputController getInput() { return input; } public void setLeftGutterVisible(boolean visible) { Element gutterElement = leftGutterManager.getGutter().getGutterElement(); if (visible) { getView().addGutter(gutterElement); } else { getView().removeGutter(gutterElement); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/Spacer.java
client/src/main/java/com/google/collide/client/editor/Spacer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import collide.client.util.Elements; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.util.SortedList; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /* * TODO: Knowledge about what lines the spacer is logically linked * to which could make the system scroll intelligently, see comments in CL * 26294787 */ /** * A spacer allows a client to insert UI inbetween lines in an editor without * affecting the backing document. * */ public class Spacer { /** * Comparator for sorting spacers. */ public static class Comparator implements SortedList.Comparator<Spacer> { @Override public int compare(Spacer a, Spacer b) { return a.getLineNumber() - b.getLineNumber(); } } /** * One way comparator for sorting spacers. */ public static class OneWaySpacerComparator extends SortedList.OneWayIntComparator<Spacer> { @Override public int compareTo(Spacer s) { return value - s.getLineNumber(); } } /** A spacer's anchor is always attached to the line that follows the spacer */ private final Anchor anchor; private final Buffer buffer; private final CoordinateMap coordinateMap; /** Always use {@link #getElement()} */ private Element element; private int height; private String cssClass; Spacer(Anchor anchor, int height, CoordinateMap coordinateMap, Buffer buffer, String cssClass) { this.anchor = anchor; this.height = height; this.coordinateMap = coordinateMap; this.buffer = buffer; this.cssClass = cssClass; } /** * Return the line number this spacer is attached above. */ public int getLineNumber() { return anchor.getLineNumber(); } public Line getLine() { return anchor.getLine(); } public LineInfo getLineInfo() { return anchor.getLineInfo(); } public Anchor getAnchor() { return anchor; } /** * Return the height of this spacer, not including the line it is attached * to below. */ public int getHeight() { return height; } public void setHeight(int newHeight) { int oldHeight = height; height = newHeight; coordinateMap.handleSpacerHeightChanged(this, oldHeight); element.getStyle().setHeight(height, CSSStyleDeclaration.Unit.PX); element.getStyle().setMarginTop(-height, CSSStyleDeclaration.Unit.PX); } public void addElement(Element addElement) { getElement().appendChild(addElement); } public boolean isAttached() { return anchor.isAttached(); } @Override public String toString() { return "Spacer, height: " + height + ", line number: " + anchor.getLineNumber(); } private Element getElement() { if (element != null) { return element; } // Create div area for clients to draw inside element = Elements.createDivElement(); element.addClassName(cssClass); element.getStyle().setLeft("0px"); element.getStyle().setRight("0px"); element.getStyle().setHeight(height, CSSStyleDeclaration.Unit.PX); element.getStyle().setPosition(CSSStyleDeclaration.Position.ABSOLUTE); element.getStyle().setMarginTop(-height, CSSStyleDeclaration.Unit.PX); EventListener bubblePreventionListener = new EventListener() { @Override public void handleEvent(Event e) { e.stopPropagation(); } }; element.setOnmousedown(bubblePreventionListener); element.setOnmousemove(bubblePreventionListener); element.setOnmouseup(bubblePreventionListener); buffer.addAnchoredElement(anchor, element); return element; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/CoordinateMap.java
client/src/main/java/com/google/collide/client/editor/CoordinateMap.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.util.ListenerRegistrar.Remover; import com.google.collide.shared.util.SortedList; import com.google.collide.shared.util.SortedList.OneWayIntComparator; /** * This class takes care of mapping between the different coordinates used by * the editor. The two supported systems are: * <ul> * <li>Offset (x,y) - in pixels, relative to the top left of line 0 in the * current document. * <li>Line (line, column) - the real line number and column, taking into * account spacer objects in between lines. Lines and columns are 0-indexed. * </ul> */ class CoordinateMap implements Document.LineListener { interface DocumentSizeProvider { float getEditorCharacterWidth(); int getEditorLineHeight(); void handleSpacerHeightChanged(Spacer spacer, int oldHeight); } private static class OffsetCache { private static final SortedList.Comparator<OffsetCache> COMPARATOR = new SortedList.Comparator<OffsetCache>() { @Override public int compare(OffsetCache a, OffsetCache b) { return a.offset - b.offset; } }; private static final SortedList.OneWayIntComparator<OffsetCache> Y_OFFSET_ONE_WAY_COMPARATOR = new SortedList.OneWayIntComparator<OffsetCache>() { @Override public int compareTo(OffsetCache s) { return value - s.offset; } }; private static final SortedList.OneWayIntComparator<OffsetCache> LINE_NUMBER_ONE_WAY_COMPARATOR = new SortedList.OneWayIntComparator<OffsetCache>() { @Override public int compareTo(OffsetCache s) { return value - s.lineNumber; } }; private final int offset; private final int height; private final int lineNumber; private OffsetCache(int offset, int lineNumber, int height) { this.offset = offset; this.height = height; this.lineNumber = lineNumber; } } private static final OffsetCache BEGINNING_EMPTY_OFFSET_CACHE = new OffsetCache(0, 0, 0); private static final AnchorType SPACER_ANCHOR_TYPE = AnchorType.create(CoordinateMap.class, "spacerAnchorType"); private static final Spacer.Comparator SPACER_COMPARATOR = new Spacer.Comparator(); private static final Spacer.OneWaySpacerComparator SPACER_ONE_WAY_COMPARATOR = new Spacer.OneWaySpacerComparator(); /** Used by {@link #getPrecedingOffsetCache(int, int)} */ private static final int IGNORE = Integer.MIN_VALUE; private Document document; private DocumentSizeProvider documentSizeProvider; /** List of offset cache items, sorted by the offset */ private SortedList<OffsetCache> offsetCache; /** * True if there is at least one spacer in the editor, false otherwise (false * means a simple height / line height calculation can be used) */ private boolean requiresMapping; /** Sorted by line number */ private SortedList<Spacer> spacers; /** Summation of all spacers' heights */ private int totalSpacerHeight; /** Remover for listener */ private Remover documentLineListenerRemover; CoordinateMap(DocumentSizeProvider documentSizeProvider) { this.documentSizeProvider = documentSizeProvider; requiresMapping = false; } int convertYToLineNumber(int y) { if (y < 0) { return 0; } int lineHeight = documentSizeProvider.getEditorLineHeight(); if (!requiresMapping) { return y / lineHeight; } OffsetCache precedingOffsetCache = getPrecedingOffsetCache(y, IGNORE); int precedingOffsetCacheBottom = precedingOffsetCache.offset + precedingOffsetCache.height; int lineNumberRelativeToOffsetCacheLine = (y - precedingOffsetCacheBottom) / lineHeight; if (y < precedingOffsetCacheBottom) { // y is inside the spacer return precedingOffsetCache.lineNumber; } else { return precedingOffsetCache.lineNumber + lineNumberRelativeToOffsetCacheLine; } } /** * Returns the top of the given line. */ int convertLineNumberToY(int lineNumber) { int lineHeight = documentSizeProvider.getEditorLineHeight(); if (!requiresMapping) { return lineNumber * lineHeight; } OffsetCache precedingOffsetCache = getPrecedingOffsetCache(IGNORE, lineNumber); int precedingOffsetCacheBottom = precedingOffsetCache.offset + precedingOffsetCache.height; int offsetRelativeToOffsetCacheBottom = (lineNumber - precedingOffsetCache.lineNumber) * lineHeight; return precedingOffsetCacheBottom + offsetRelativeToOffsetCacheBottom; } /** * Returns the first {@link OffsetCache} that is positioned less than or equal * to {@code y} or {@code lineNumber}. This methods fills the * {@link #offsetCache} if necessary ensuring the returned {@link OffsetCache} * is up-to-date. * * @param y the y, or {@link #IGNORE} if looking up by {@code lineNumber} * @param lineNumber the line number, or {@link #IGNORE} if looking up by * {@code y} */ private OffsetCache getPrecedingOffsetCache(int y, int lineNumber) { assert (y != IGNORE && lineNumber == IGNORE) || (lineNumber != IGNORE && y == IGNORE); final int lineHeight = documentSizeProvider.getEditorLineHeight(); OffsetCache previousOffsetCache; if (y != IGNORE) { previousOffsetCache = getCachedPrecedingOffsetCacheImpl(OffsetCache.Y_OFFSET_ONE_WAY_COMPARATOR, y); } else { previousOffsetCache = getCachedPrecedingOffsetCacheImpl(OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR, lineNumber); } if (previousOffsetCache == null) { if (spacers.size() > 0 && spacers.get(0).getLineNumber() == 0) { previousOffsetCache = createOffsetCache(0, 0, spacers.get(0).getHeight()); } else { previousOffsetCache = BEGINNING_EMPTY_OFFSET_CACHE; } } /* * Optimization so the common case that the target has previously been * computed requires no more computation */ int offsetCacheSize = offsetCache.size(); if (offsetCacheSize > 0 && isTargetEarlierThanOffsetCache(y, lineNumber, offsetCache.get(offsetCacheSize - 1))) { return previousOffsetCache; } // This will return this offset cache's matching spacer int spacerPos = getPrecedingSpacerIndex(previousOffsetCache.lineNumber); /* * We want the spacer following this offset cache's spacer, or the first * spacer if none were found */ spacerPos++; for (int n = spacers.size(); spacerPos < n; spacerPos++) { Spacer curSpacer = spacers.get(spacerPos); int previousOffsetCacheBottom = previousOffsetCache.offset + previousOffsetCache.height; int simpleLinesHeight = (curSpacer.getLineNumber() - previousOffsetCache.lineNumber) * lineHeight; if (simpleLinesHeight == 0) { Log.warn(Spacer.class, "More than one spacer on line " + previousOffsetCache.lineNumber); } // Create an offset cache for this spacer OffsetCache curOffsetCache = createOffsetCache(previousOffsetCacheBottom + simpleLinesHeight, curSpacer.getLineNumber(), curSpacer.getHeight()); if (isTargetEarlierThanOffsetCache(y, lineNumber, curOffsetCache)) { return previousOffsetCache; } previousOffsetCache = curOffsetCache; } return previousOffsetCache; } /** * Returns the {@link OffsetCache} instance in list that has the greatest * value less than or equal to the given {@code value}. Returns null if there * isn't one. * * This should only be used by {@link #getPrecedingOffsetCache(int, int)}. */ private OffsetCache getCachedPrecedingOffsetCacheImpl( OneWayIntComparator<OffsetCache> comparator, int value) { comparator.setValue(value); int index = offsetCache.findInsertionIndex(comparator, false); return index >= 0 ? offsetCache.get(index) : null; } private boolean isTargetEarlierThanOffsetCache(int y, int lineNumber, OffsetCache offsetCache) { return ((y != IGNORE && y < offsetCache.offset) || (lineNumber != IGNORE && lineNumber < offsetCache.lineNumber)); } private OffsetCache createOffsetCache(int offset, int lineNumber, int height) { OffsetCache createdOffsetCache = new OffsetCache(offset, lineNumber, height); offsetCache.add(createdOffsetCache); return createdOffsetCache; } private int getPrecedingSpacerIndex(int lineNumber) { SPACER_ONE_WAY_COMPARATOR.setValue(lineNumber); return spacers.findInsertionIndex(SPACER_ONE_WAY_COMPARATOR, false); } /** * Adds a spacer above the given lineInfo line with height heightPx and * returns the created Spacer object. * * @param lineInfo the line before which the spacer will be inserted * @param height the height in pixels of the spacer */ Spacer createSpacer(LineInfo lineInfo, int height, Buffer buffer, String cssClass) { int lineNumber = lineInfo.number(); // create an anchor on the current line Anchor anchor = document.getAnchorManager().createAnchor(SPACER_ANCHOR_TYPE, lineInfo.line(), lineNumber, AnchorManager.IGNORE_COLUMN); anchor.setRemovalStrategy(RemovalStrategy.SHIFT); // account for the height of the line the spacer is on Spacer spacer = new Spacer(anchor, height, this, buffer, cssClass); spacers.add(spacer); totalSpacerHeight += height; invalidateLineNumberAndFollowing(lineNumber); requiresMapping = true; return spacer; } boolean removeSpacer(Spacer spacer) { int lineNumber = spacer.getLineNumber(); if (spacers.remove(spacer)) { document.getAnchorManager().removeAnchor(spacer.getAnchor()); totalSpacerHeight -= spacer.getHeight(); invalidateLineNumberAndFollowing(lineNumber - 1); updateRequiresMapping(); return true; } return false; } void handleDocumentChange(Document document) { if (documentLineListenerRemover != null) { documentLineListenerRemover.remove(); } this.document = document; spacers = new SortedList<Spacer>(SPACER_COMPARATOR); offsetCache = new SortedList<OffsetCache>(OffsetCache.COMPARATOR); documentLineListenerRemover = document.getLineListenerRegistrar().add(this); requiresMapping = false; // starts with no items in list totalSpacerHeight = 0; } @Override public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) { invalidateLineNumberAndFollowing(lineNumber); } @Override public void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines) { invalidateLineNumberAndFollowing(lineNumber); } /** * Call this after any line changes (adding/deleting lines, changing line * heights). Only invalidate (delete) cache items >= lineNumber, don't * recalculate. */ void invalidateLineNumberAndFollowing(int lineNumber) { OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR.setValue(lineNumber); int insertionIndex = offsetCache.findInsertionIndex(OffsetCache.LINE_NUMBER_ONE_WAY_COMPARATOR); offsetCache.removeThisAndFollowing(insertionIndex); } private void updateRequiresMapping() { // check to change active status requiresMapping = spacers.size() > 0; } int getTotalSpacerHeight() { return totalSpacerHeight; } void handleSpacerHeightChanged(Spacer spacer, int oldHeight) { totalSpacerHeight -= oldHeight; totalSpacerHeight += spacer.getHeight(); invalidateLineNumberAndFollowing(spacer.getLineNumber()); documentSizeProvider.handleSpacerHeightChanged(spacer, oldHeight); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/TextActions.java
client/src/main/java/com/google/collide/client/editor/TextActions.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.input.CommonActions; import com.google.collide.client.editor.input.DefaultActionExecutor; import com.google.collide.client.editor.input.InputScheme; import com.google.collide.client.editor.input.Shortcut; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.util.LineUtils; /** * Implementation of some common textual actions. */ public class TextActions extends DefaultActionExecutor { public static final TextActions INSTANCE = new TextActions(); private TextActions() { addAction(CommonActions.SPLIT_LINE, new Shortcut(){ @Override public boolean event(InputScheme scheme, SignalEvent event) { splitLine(scheme.getInputController().getEditor()); return true; } }); addAction(CommonActions.START_NEW_LINE, new Shortcut(){ @Override public boolean event(InputScheme scheme, SignalEvent event) { startNewLine(scheme.getInputController().getEditor()); return true; } }); } private void startNewLine(Editor editor) { SelectionModel selection = editor.getSelection(); selection.deselect(); Line line = selection.getCursorLine(); int lineNumber = selection.getCursorLineNumber(); int lastCursorColumn = LineUtils.getLastCursorColumn(line); selection.setCursorPosition(new LineInfo(line, lineNumber), lastCursorColumn); editor.getEditorDocumentMutator().insertText(line, lineNumber, lastCursorColumn, "\n"); } private void splitLine(Editor editor) { // TODO: Add language specific logic (i.e. string splitting). SelectionModel selection = editor.getSelection(); Position[] selectionRange = selection.getSelectionRange(false); Position cursor = selectionRange[0]; editor.getEditorDocumentMutator().insertText(cursor.getLine(), cursor.getLineNumber(), cursor.getColumn(), "\n", true); selection.setCursorPosition(cursor.getLineInfo(), cursor.getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/EditorUndoManager.java
client/src/main/java/com/google/collide/client/editor/EditorUndoManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import java.util.List; import org.waveprotocol.wave.model.operation.OperationPair; import org.waveprotocol.wave.model.operation.TransformException; import org.waveprotocol.wave.model.undo.UndoManagerImpl; import org.waveprotocol.wave.model.undo.UndoManagerImpl.Algorithms; import org.waveprotocol.wave.model.undo.UndoManagerPlus; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.dto.DocOp; import com.google.collide.dto.client.ClientDocOpFactory; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.document.util.PositionUtils; 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.Inverter; import com.google.collide.shared.ot.Transformer; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; // TODO: restore selection/cursor /** * A class to manage the editor's undo/redo functionality. * */ public class EditorUndoManager { /** * Delegates to the document operation algorithms when requested by the Wave * undo library. */ private static final UndoManagerImpl.Algorithms<DocOp> ALGORITHMS = new Algorithms<DocOp>() { @Override public DocOp invert(DocOp operation) { return Inverter.invert(ClientDocOpFactory.INSTANCE, operation); } @Override public DocOp compose(List<DocOp> operationsReverse) { try { return Composer.compose(ClientDocOpFactory.INSTANCE, operationsReverse); } catch (ComposeException e) { throw new RuntimeException(e); } } @Override public OperationPair<DocOp> transform(DocOp op1, DocOp op2) throws TransformException { try { com.google.collide.shared.ot.OperationPair ourPair = Transformer.transform(ClientDocOpFactory.INSTANCE, op1, op2); return new OperationPair<DocOp>(ourPair.clientOp(), ourPair.serverOp()); } catch (com.google.collide.shared.ot.Transformer.TransformException e) { throw new TransformException(e); } } }; public static EditorUndoManager create(Editor editor, Document document, SelectionModel selection) { return new EditorUndoManager(editor, document, selection, new UndoManagerImpl<DocOp>(ALGORITHMS)); } /* * TODO: think about which other events should cause a * checkpoint. Push out to a toplevel class if it gets complicated. */ /** * Produces undo checkpoints at opportune times, such as when the user * explicitly moves the cursor (arrow keys or mouse click) or when the user's * text mutations change from delete to insert. */ private class CheckpointProducer implements SelectionModel.CursorListener, Editor.BeforeTextListener, Editor.TextListener { private TextChange.Type previousTextChangeType; @Override public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) { if (isExplicitChange) { undoManager.checkpoint(); } } @Override public void onBeforeTextChange(TextChange textChange) { if (previousTextChangeType != textChange.getType()) { undoManager.checkpoint(); } previousTextChangeType = textChange.getType(); } @Override public void onTextChange(TextChange textChange) { if (textChange.getText().contains("\n")) { /* * Checkpoint after newlines which tends to be a good granularity for * typical editor use */ undoManager.checkpoint(); } } } private final CheckpointProducer checkpointProducer = new CheckpointProducer(); private final Document document; private final Document.TextListener documentTextListener = new Document.TextListener() { @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { if (isMutatingDocument || editor.getEditorDocumentMutator().isMutatingDocument()) { // We will handle this text change in the editor text change callback return; } for (int i = 0, n = textChanges.size(); i < n; i++) { TextChange textChange = textChanges.get(i); // This is a collaborator doc op, which is not undoable by us undoManager.nonUndoableOp(DocOpUtils.createFromTextChange(ClientDocOpFactory.INSTANCE, textChange)); } } }; private final Editor editor; private final Editor.TextListener editorTextListener = new Editor.TextListener() { @Override public void onTextChange(TextChange textChange) { if (isMutatingDocument) { // We caused this text change, so don't handle it return; } // This is a user document mutation that is undoable undoManager.undoableOp(DocOpUtils.createFromTextChange(ClientDocOpFactory.INSTANCE, textChange)); } }; private boolean isMutatingDocument; private final JsonArray<ListenerRegistrar.Remover> listenerRemovers = JsonCollections.createArray(); private final SelectionModel selection; private final UndoManagerPlus<DocOp> undoManager; private EditorUndoManager(Editor editor, Document document, SelectionModel selection, UndoManagerPlus<DocOp> undoManager) { this.document = document; this.editor = editor; this.selection = selection; this.undoManager = undoManager; listenerRemovers.add(document.getTextListenerRegistrar().add(documentTextListener)); listenerRemovers.add(editor.getTextListenerRegistrar().add(editorTextListener)); listenerRemovers.add(selection.getCursorListenerRegistrar().add(checkpointProducer)); listenerRemovers.add(editor.getBeforeTextListenerRegistrar().add(checkpointProducer)); listenerRemovers.add(editor.getTextListenerRegistrar().add(checkpointProducer)); } boolean isMutatingDocument() { return isMutatingDocument; } void undo() { DocOp undoDocOp = undoManager.undo(); if (undoDocOp == null) { return; } applyToDocument(undoDocOp); } void redo() { DocOp redoDocOp = undoManager.redo(); if (redoDocOp == null) { return; } applyToDocument(redoDocOp); } void teardown() { for (int i = 0, n = listenerRemovers.size(); i < n; i++) { listenerRemovers.get(i).remove(); } } private void applyToDocument(DocOp docOp) { JsonArray<TextChange> textChanges; isMutatingDocument = true; try { /* * Mutate via the document (instead of editor) since we don't want this to * be affected by autoindentation, etc. We also don't want to replace the * text in the selection, and the document's mutator will never do this. */ textChanges = DocOpApplier.apply(docOp, document, document); } finally { isMutatingDocument = false; } // a retain only doc-op will not produce a text-change if (textChanges.size() == 0) { return; } /* * There can theoretically be multiple text changes, but we just set * selection to the first */ TextChange textChange = textChanges.get(0); Position endPosition = new Position(new LineInfo(textChange.getEndLine(), textChange.getEndLineNumber()), textChange.getEndColumn()); if (textChange.getType() == TextChange.Type.INSERT) { endPosition = PositionUtils.getPosition(endPosition, 1); } selection.setSelection(new LineInfo(textChange.getLine(), textChange.getLineNumber()), textChange.getColumn(), endPosition.getLineInfo(), endPosition.getColumn()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/FocusManager.java
client/src/main/java/com/google/collide/client/editor/FocusManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import collide.client.util.Elements; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * Tracks the focus state of the editor. * */ public class FocusManager { /** * A listener that is called when the editor receives or loses focus. */ public interface FocusListener { void onFocusChange(boolean hasFocus); } private final ListenerManager<FocusManager.FocusListener> focusListenerManager = ListenerManager .create(); private boolean hasFocus; private final Element inputElement; FocusManager(Buffer buffer, Element inputElement) { this.inputElement = inputElement; attachEventHandlers(buffer); hasFocus = inputElement.equals(Elements.getActiveElement()); } private void attachEventHandlers(Buffer buffer) { inputElement.addEventListener(Event.FOCUS, new EventListener() { private final Dispatcher<FocusManager.FocusListener> dispatcher = new Dispatcher<FocusManager.FocusListener>() { @Override public void dispatch(FocusListener listener) { listener.onFocusChange(true); } }; @Override public void handleEvent(Event evt) { hasFocus = true; focusListenerManager.dispatch(dispatcher); } }, false); inputElement.addEventListener(Event.BLUR, new EventListener() { private final Dispatcher<FocusManager.FocusListener> dispatcher = new Dispatcher<FocusManager.FocusListener>() { @Override public void dispatch(FocusListener listener) { listener.onFocusChange(false); } }; @Override public void handleEvent(Event evt) { hasFocus = false; focusListenerManager.dispatch(dispatcher); } }, false); buffer.getMouseClickListenerRegistrar().add(new Buffer.MouseClickListener() { @Override public void onMouseClick(int x, int y) { focus(); } }); } public ListenerRegistrar<FocusManager.FocusListener> getFocusListenerRegistrar() { return focusListenerManager; } public boolean hasFocus() { return hasFocus; } public void focus() { inputElement.focus(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/ElementManager.java
client/src/main/java/com/google/collide/client/editor/ElementManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonIntegerMap; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorManager.AnchorVisitor; import com.google.collide.shared.document.anchor.AnchorUtils; import com.google.collide.shared.document.anchor.ReadOnlyAnchor; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; // TODO: support RangeAnchoredElements /** * A manager that allows for adding and removing elements to some given * container element. This manager is capable of adding elements that are * anchored to a point or to a range. * * Some restrictions of anchored elements: * <ul> * <li>An anchor cannot be used to anchor multiple elements</li> * <li>Anchors must be assigned a line number (though this can be loosened if a * use case arises)</li> * </ul> */ public class ElementManager { private final ReadOnlyAnchor.ShiftListener anchorShiftedListener = new ReadOnlyAnchor.ShiftListener() { @Override public void onAnchorShifted(ReadOnlyAnchor anchor) { updateAnchoredElements(anchor); } }; private final ReadOnlyAnchor.MoveListener anchorMovedListener = new ReadOnlyAnchor.MoveListener() { @Override public void onAnchorMoved(ReadOnlyAnchor anchor) { updateAnchoredElements(anchor); } }; private final ReadOnlyAnchor.RemoveListener anchorRemovalListener = new ReadOnlyAnchor.RemoveListener() { @Override public void onAnchorRemoved(ReadOnlyAnchor anchor) { JsonArray<Element> elements = anchoredElements.get(anchor.getId()); for (int i = 0, n = elements.size(); i < n; i++) { removeAnchoredElement(anchor, elements.get(i)); } } }; private final Buffer buffer; private final Element container; private final JsonIntegerMap<JsonArray<Element>> anchoredElements = JsonCollections.createIntegerMap(); private final JsonArray<ReadOnlyAnchor> anchoredElementAnchors = JsonCollections.createArray(); private final Renderer.LineLifecycleListener renderedLineLifecycleListener = new Renderer.LineLifecycleListener() { private final AnchorVisitor lineCreatedAnchorVisitor = new AnchorVisitor() { @Override public void visitAnchor(Anchor anchor) { JsonArray<Element> elements = anchoredElements.get(anchor.getId()); if (elements != null) { for (int i = 0, n = elements.size(); i < n; i++) { Element element = elements.get(i); attachElement(element); positionElementToAnchorTopLeft(anchor, element); } } } }; private final AnchorVisitor lineShiftedAnchorVisitor = new AnchorVisitor() { @Override public void visitAnchor(Anchor anchor) { JsonArray<Element> elements = anchoredElements.get(anchor.getId()); if (elements != null) { for (int i = 0, n = elements.size(); i < n; i++) { updateAnchoredElement(anchor, elements.get(i)); } } } }; private final AnchorVisitor lineGarbageCollectedAnchorVisitor = new AnchorVisitor() { @Override public void visitAnchor(Anchor anchor) { JsonArray<Element> elements = anchoredElements.get(anchor.getId()); if (elements != null) { for (int i = 0, n = elements.size(); i < n; i++) { detachElement(elements.get(i)); } } } }; @Override public void onRenderedLineGarbageCollected(Line line) { AnchorUtils.visitAnchorsOnLine(line, lineGarbageCollectedAnchorVisitor); } @Override public void onRenderedLineCreated(Line line, int lineNumber) { AnchorUtils.visitAnchorsOnLine(line, lineCreatedAnchorVisitor); } @Override public void onRenderedLineShifted(Line line, int lineNumber) { /* * TODO: Given this callback exists now, do we really * need to require anchors with line numbers? */ AnchorUtils.visitAnchorsOnLine(line, lineShiftedAnchorVisitor); } }; private ListenerRegistrar.Remover rendererListenerRemover; private final JsonArray<Element> unmanagedElements = JsonCollections.createArray(); private ViewportModel viewport; public ElementManager(Element container, Buffer buffer) { this.container = container; this.buffer = buffer; } public void handleDocumentChanged(ViewportModel viewport, Renderer renderer) { if (rendererListenerRemover != null) { rendererListenerRemover.remove(); } removeAnchoredElements(); detachElements(unmanagedElements); unmanagedElements.clear(); this.viewport = viewport; rendererListenerRemover = renderer.getLineLifecycleListenerRegistrar().add(renderedLineLifecycleListener); } public void addAnchoredElement(ReadOnlyAnchor anchor, Element element) { if (!anchor.hasLineNumber()) { throw new IllegalArgumentException( "The given anchor does not have a line number; create it with line numbers"); } JsonArray<Element> elements = anchoredElements.get(anchor.getId()); if (elements == null) { elements = JsonCollections.createArray(); anchoredElements.put(anchor.getId(), elements); anchoredElementAnchors.add(anchor); anchor.getReadOnlyShiftListenerRegistrar().add(anchorShiftedListener); anchor.getReadOnlyMoveListenerRegistrar().add(anchorMovedListener); anchor.getReadOnlyRemoveListenerRegistrar().add(anchorRemovalListener); } else if (elements.contains(element)) { // Already anchored, do nothing return; } elements.add(element); initializeElementForBeingManaged(element); updateAnchoredElement(anchor, element); } public void removeAnchoredElement(ReadOnlyAnchor anchor, Element element) { JsonArray<Element> elements = anchoredElements.get(anchor.getId()); if (elements == null || !elements.remove(element)) { return; } if (elements.size() == 0) { anchor.getReadOnlyShiftListenerRegistrar().remove(anchorShiftedListener); anchor.getReadOnlyMoveListenerRegistrar().remove(anchorMovedListener); anchor.getReadOnlyRemoveListenerRegistrar().remove(anchorRemovalListener); anchoredElements.erase(anchor.getId()); anchoredElementAnchors.remove(anchor); } detachElement(element); } private void removeAnchoredElements() { while (anchoredElementAnchors.size() > 0) { ReadOnlyAnchor anchor = anchoredElementAnchors.get(0); JsonArray<Element> elements = anchoredElements.get(anchor.getId()); for (int i = 0, n = elements.size(); i < n; i++) { removeAnchoredElement(anchor, elements.get(i)); } } } public void addUnmanagedElement(Element element) { unmanagedElements.add(element); attachElement(element); } public void removeUnmanagedElement(Element element) { unmanagedElements.remove(element); detachElement(element); } private void initializeElementForBeingManaged(Element element) { element.getStyle().setPosition(CSSStyleDeclaration.Position.ABSOLUTE); } private void updateAnchoredElements(ReadOnlyAnchor anchor) { JsonArray<Element> elements = anchoredElements.get(anchor.getId()); if (elements != null) { for (int i = 0, n = elements.size(); i < n; i++) { updateAnchoredElement(anchor, elements.get(i)); } } } /** * Renders an anchored element intelligently; adds it to the DOM when it is in * the viewport and removes it once it leaves the viewport. */ private void updateAnchoredElement(ReadOnlyAnchor anchor, Element element) { /* * We only want the line number if the anchor is in the viewport, and this * is a quick way of achieving that */ int lineNumberGuess = LineUtils.getCachedLineNumber(anchor.getLine()); boolean isInViewport = lineNumberGuess != -1 && lineNumberGuess >= viewport.getTopLineNumber() && lineNumberGuess <= viewport.getBottomLineNumber(); boolean isRendered = element.getParentElement() != null; if (isInViewport && !isRendered) { // Anchor moved into the viewport attachElement(element); positionElementToAnchorTopLeft(anchor, element); } else if (isRendered && !isInViewport) { // Anchor moved out of the viewport detachElement(element); } else if (isInViewport) { // Anchor was and is in viewport, reposition positionElementToAnchorTopLeft(anchor, element); } } private void positionElementToAnchorTopLeft(ReadOnlyAnchor anchor, Element element) { CSSStyleDeclaration style = element.getStyle(); style.setTop(buffer.convertLineNumberToY(anchor.getLineNumber()), CSSStyleDeclaration.Unit.PX); int column = anchor.getColumn(); if (column != AnchorManager.IGNORE_COLUMN) { style.setLeft(buffer.convertColumnToX(anchor.getLine(), column), CSSStyleDeclaration.Unit.PX); } } private void attachElement(Element element) { container.appendChild(element); } private void detachElements(JsonArray<Element> elements) { for (int i = 0, n = elements.size(); i < n; i++) { detachElement(elements.get(i)); } } private void detachElement(Element element) { if (container.contains(element)) { container.removeChild(element); } } public void repositionAnchoredElementsWithColumn() { for (int i = 0, n = anchoredElementAnchors.size(); i < n; i++) { ReadOnlyAnchor anchor = anchoredElementAnchors.get(i); if (!anchor.hasColumn()) { continue; } JsonArray<Element> elements = anchoredElements.get(anchor.getId()); for (int elementsPos = 0, elementsSize = elements.size(); elementsPos < elementsSize; elementsPos++) { positionElementToAnchorTopLeft(anchor, elements.get(elementsPos)); } } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/EditorContext.java
client/src/main/java/com/google/collide/client/editor/EditorContext.java
package com.google.collide.client.editor; import com.google.collide.client.editor.renderer.LineNumberRenderer; import com.google.collide.client.editor.search.SearchMatchRenderer; import com.google.collide.client.editor.selection.CursorView; import com.google.collide.client.editor.selection.SelectionLineRenderer; import com.google.collide.client.util.UserActivityManager; public interface EditorContext <R extends Editor.Resources & SearchMatchRenderer.Resources & SelectionLineRenderer.Resources & LineNumberRenderer.Resources & CursorView.Resources & Buffer.Resources> { UserActivityManager getUserActivityManager(); R getResources(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/MouseWheelRedirector.java
client/src/main/java/com/google/collide/client/editor/MouseWheelRedirector.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import org.waveprotocol.wave.client.common.util.UserAgent; import collide.client.util.BrowserUtils; import com.google.collide.client.editor.Buffer.ScrollListener; import com.google.collide.json.client.Jso; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /* * We want to behave as close to native scrolling as possible, but still prevent * flickering (without expanding the viewport/prerendering lines). The simplest * approach is to capture the amount of scroll per mousewheel, and manually * scroll the buffer. * * There is a known issue with ChromeOS where it sends a deltaWheel of +/-120 * regardless of how much it will actually scroll. See * http://code.google.com/p/chromium-os/issues/detail?id=23607 . Because of * this, we cannot properly redirect mousewheels on ChromeOS. We disable this * behavior which allows ChromeOS to have native-feeling scrolling (albeit * with flicker.) */ /** * An object that intercepts mousewheel events that would have otherwise gone to * the scrollable layer in the buffer. Instead, we manually scroll the buffer * * <p>The purpose is to prevent flickering of the newly scrolled region. If the * scrollable element takes the scroll, that element will be scrolled before we * can fill it with contents. Therefore, there will be white displayed for a * split-second, and then text. */ class MouseWheelRedirector { public static void redirect(Buffer buffer, Element scrollableElement) { // ChromeOS early exit (see class implementation comment) if (BrowserUtils.isChromeOs()) { return; } new MouseWheelRedirector(buffer).attachEventHandlers(scrollableElement); } /** * Default value for {@link #mouseWheelToScrollDelta} indicating it has not * been defined yet. */ private static final int UNDEFINED = 0; private final Buffer buffer; /** * The magnitude to scroll per wheelDelta unit. Even though mousewheel events * have wheelDelta in multiples of 120, this is the magnitude of a scroll * corresponding to 1. */ private double mouseWheelToScrollDelta = UNDEFINED; private MouseWheelRedirector(Buffer buffer) { this.buffer = buffer; } private static native int getWheelDeltaX(Event event) /*-{ // if using webkit (such as in Chrome) we can detect horizontal scroll if (event.wheelDeltaX) { return event.wheelDeltaX; } else { return 0; } }-*/; private void attachEventHandlers(Element scrollableElement) { /* * The MOUSEWHEEL does not exist on FF (it has DOMMouseScroll which we don't * bother to support). This means FF mousewheel scrolling will flicker. */ scrollableElement.addEventListener(Event.MOUSEWHEEL, new EventListener() { @Override public void handleEvent(Event mouseWheelEvent) { // MouseWheelEvent mouseWheelEvent = (MouseWheelEvent) evt; /* * The negative is so the deltaX,Y are positive when the scroll delta * is. That is, a positive "deltaY" will scroll down. */ int deltaY = -((Jso) mouseWheelEvent).getIntField("wheelDeltaY"); int deltaX = -((Jso) mouseWheelEvent).getIntField("wheelDeltaX"); /* * If the deltaY is 0, this is probably a horizontal-only scroll, in * which case we let it proceed as normal (no preventDefault, no manual * scrolling, etc.) */ if (deltaY != 0) { if (mouseWheelToScrollDelta == UNDEFINED) { captureFirstMouseWheelToScrollDelta(deltaY); } else { /* * There is a chance that we have both a horizontal and vertical * scroll here. For vertical scroll, we must manually scroll to * prevent flickering. Since we'll need to preventDefault, we * must scroll the event's horizontal component too (otherwise * the intended horizontal scroll would be lost.) */ buffer.setScrollTop(buffer.getScrollTop() + (int) (mouseWheelToScrollDelta * deltaY)); buffer.setScrollLeft(buffer.getScrollLeft() + (int) (mouseWheelToScrollDelta * deltaX)); mouseWheelEvent.preventDefault(); } } } }, false); } private void captureFirstMouseWheelToScrollDelta(final int wheelDelta) { if (UserAgent.debugUserAgentString().contains("Chrome/17") && UserAgent.isMac() && (wheelDelta < 120 || (wheelDelta % 120) != 0)) { /* * This is a workaround for Mac trackpads that typically send the actual pixel scroll amount * instead of a factor of 120. It seems like without this special check, we would still get a * sane mapping for mouseWheelToScrollDelta, but if the initial touchpad scroll is really * fast, we get a mouseWheelToScrollDelta that is way too big. * * Chrome 18 and above fix this with a fixed constant of 1 to 3, so we don't need special * casing. (17 is stable at the time of this writing.) */ mouseWheelToScrollDelta = 1; } else { final int initialScrollTop = buffer.getScrollTop(); buffer.getScrollListenerRegistrar().add(new ScrollListener() { @Override public void onScroll(Buffer buffer, int scrollTop) { mouseWheelToScrollDelta = Math.abs(((float) scrollTop - initialScrollTop) / wheelDelta); buffer.getScrollListenerRegistrar().remove(this); } }); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/EditorDocumentMutator.java
client/src/main/java/com/google/collide/client/editor/EditorDocumentMutator.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import com.google.collide.client.editor.Editor.BeforeTextListener; import com.google.collide.client.editor.Editor.TextListener; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; /** * A document mutator for the editor which will notify editor text listeners * whenever a editor-initiated document mutation occurs. * */ public class EditorDocumentMutator implements DocumentMutator { private final ListenerManager<BeforeTextListener> beforeTextListenerManager = ListenerManager .create(); private final Editor editor; private boolean isMutatingDocument; private final ListenerManager<TextListener> textListenerManager = ListenerManager.create(); EditorDocumentMutator(Editor editor) { this.editor = editor; } @Override public TextChange deleteText(Line line, int column, int deleteCount) { return deleteText(line, line.getDocument().getLineFinder().findLine(line).number(), column, deleteCount); } @Override public TextChange deleteText(Line line, int lineNumber, int column, int deleteCount) { String deletedText = editor.getDocument().getText(line, column, deleteCount); return deleteText(line, lineNumber, column, deletedText); } private TextChange deleteText(Line line, int lineNumber, int column, String deletedText) { if (editor.isReadOnly()) { return null; } TextChange textChange = TextChange.createDeletion(line, lineNumber, column, deletedText); dispatchBeforeTextChange(textChange); isMutatingDocument = true; editor.getDocument().deleteText(line, lineNumber, column, deletedText.length()); isMutatingDocument = false; dispatchTextChange(textChange); return textChange; } /** * If there is a selection, the inserted text will replace the selected text. * * @see DocumentMutator#insertText(Line, int, String) */ @Override public TextChange insertText(Line line, int column, String text) { return insertText(line, line.getDocument().getLineFinder().findLine(line).number(), column, text); } @Override public TextChange insertText(Line line, int lineNumber, int column, String text) { return insertText(line, lineNumber, column, text, true); } @Override public TextChange insertText(Line line, int lineNumber, int column, String text, boolean canReplaceSelection) { if (editor.isReadOnly()) { return null; } TextChange textChange = null; SelectionModel selection = editor.getSelection(); if (canReplaceSelection && selection.hasSelection()) { Position[] selectionRange = selection.getSelectionRange(true); /* * TODO: this isn't going to scale for document-sized * selections, need to change some APIs */ Line beginLine = selectionRange[0].getLine(); int beginLineNumber = selectionRange[0].getLineNumber(); int beginColumn = selectionRange[0].getColumn(); String textToDelete = LineUtils.getText(beginLine, beginColumn, selectionRange[1].getLine(), selectionRange[1].getColumn()); textChange = deleteText(beginLine, beginLineNumber, beginColumn, textToDelete); // The insertion should go where the selection was line = beginLine; lineNumber = beginLineNumber; column = beginColumn; } if (text.length() == 0) { return textChange; } /* * The contract for the before text change event is to pass the insertion * line as the "last" line since the text hasn't been inserted yet. */ textChange = TextChange.createInsertion(line, lineNumber, column, line, lineNumber, text); dispatchBeforeTextChange(textChange); isMutatingDocument = true; editor.getDocument().insertText(line, lineNumber, column, text); isMutatingDocument = false; dispatchTextChange(textChange); return textChange; } /** * Returns true if this mutator is currently mutating the document. */ public boolean isMutatingDocument() { return isMutatingDocument; } void dispatchBeforeTextChange(final TextChange textChange) { beforeTextListenerManager.dispatch(new Dispatcher<BeforeTextListener>() { @Override public void dispatch(BeforeTextListener listener) { listener.onBeforeTextChange(textChange); } }); } void dispatchTextChange(final TextChange textChange) { textListenerManager.dispatch(new Dispatcher<TextListener>() { @Override public void dispatch(TextListener listener) { listener.onTextChange(textChange); } }); } ListenerRegistrar<BeforeTextListener> getBeforeTextListenerRegistrar() { return beforeTextListenerManager; } ListenerRegistrar<TextListener> getTextListenerRegistrar() { return textListenerManager; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/MouseHoverManager.java
client/src/main/java/com/google/collide/client/editor/MouseHoverManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import org.waveprotocol.wave.client.common.util.SignalEvent; import org.waveprotocol.wave.client.common.util.UserAgent; import collide.client.common.Constants; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.ListenerRegistrar.Remover; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.user.client.Timer; import elemental.events.Event; /** * Manages mouse hover events, optionally when a key modifier combination is * pressed. * * <p>This class fires mouse hover events asynchronously, with the delay of * {@link Constants#MOUSE_HOVER_DELAY} milliseconds. The reason is that it is * quite expensive to calculate LineInfo and column number from a mouse move * event's {x,y} pair. */ public class MouseHoverManager { public enum KeyModifier { NONE(0), SHIFT(KeyCodes.KEY_SHIFT), CTRL(KeyCodes.KEY_CTRL), ALT(KeyCodes.KEY_ALT), META(91); /** * @return {@link #META} key modifier for Mac OS, or {@link #CTRL} otherwise */ public static KeyModifier ctrlOrMeta() { return UserAgent.isMac() ? KeyModifier.META : KeyModifier.CTRL; } private final int keyCode; private KeyModifier(int keyCode) { this.keyCode = keyCode; } public int getKeyCode() { return keyCode; } } public interface MouseHoverListener { void onMouseHover(int x, int y, LineInfo lineInfo, int column); } private final Editor editor; private final JsonStringMap<ListenerManager<MouseHoverListener>> listenerManagers = JsonCollections.createMap(); /** * Current key combination that we will dispatch the mouse hover events for. * If {@code null}, no mouse hover events should be dispatched just yet. */ private KeyModifier lastKeyModifier = KeyModifier.NONE; private ListenerRegistrar.Remover keyPressListenerRemover; private ListenerRegistrar.Remover mouseMoveListenerRemover; private ListenerRegistrar.Remover mouseOutListenerRemover; private ListenerRegistrar.Remover nativeKeyUpListenerRemover; private final Editor.NativeKeyUpListener keyUpListener = new Editor.NativeKeyUpListener() { @Override public boolean onNativeKeyUp(Event event) { /* * Consider any key-up event releases the key modifier combination, to * avoid tricky stale states. */ releaseLastKeyModifier(); // Do not interfere with the editor input. return false; } }; private final Editor.KeyListener keyPressListener = new Editor.KeyListener() { @Override public boolean onKeyPress(SignalEvent signal) { KeyModifier newKeyModifier = null; JsonArray<String> modifierKeys = listenerManagers.getKeys(); for (int i = 0, n = modifierKeys.size(); i < n; ++i) { KeyModifier keyModifier = KeyModifier.valueOf(modifierKeys.get(i)); if (keyModifier.getKeyCode() == signal.getKeyCode()) { newKeyModifier = keyModifier; break; } } if (lastKeyModifier != newKeyModifier) { lastKeyModifier = newKeyModifier; updateEditorListeners(); } // Do not interfere with the editor input. return false; } }; private class MouseListenersImpl extends Timer implements Buffer.MouseMoveListener, Buffer.MouseOutListener { private int x; private int y; @Override public void run() { handleOnMouseMove(x, y); } @Override public void onMouseMove(int x, int y) { this.x = x; this.y = y; schedule(Constants.MOUSE_HOVER_DELAY); } @Override public void onMouseOut() { // We are no longer hovering the editor's buffer. cancel(); // We can not track the keyboard outside the buffer, just reset the state. releaseLastKeyModifier(); } } private final MouseListenersImpl mouseListener = new MouseListenersImpl(); MouseHoverManager(Editor editor) { this.editor = editor; } public Remover addMouseHoverListener(MouseHoverListener listener) { return addMouseHoverListener(KeyModifier.NONE, listener); } public Remover addMouseHoverListener( final KeyModifier keyModifier, final MouseHoverListener listener) { String key = keyModifier.toString(); ListenerManager<MouseHoverListener> manager = listenerManagers.get(key); if (manager == null) { manager = ListenerManager.create(); listenerManagers.put(key, manager); } final Remover listenerRemover = manager.add(listener); updateEditorListeners(); return new Remover() { @Override public void remove() { removeMouseHoverListener(listenerRemover, keyModifier, listener); } }; } private void removeMouseHoverListener( Remover listenerRemover, KeyModifier keyModifier, MouseHoverListener listener) { String key = keyModifier.toString(); ListenerManager<MouseHoverListener> manager = listenerManagers.get(key); if (manager == null) { return; } listenerRemover.remove(); if (manager.getCount() == 0) { listenerManagers.remove(key); } updateEditorListeners(); } private void releaseLastKeyModifier() { if (lastKeyModifier != KeyModifier.NONE) { lastKeyModifier = KeyModifier.NONE; updateEditorListeners(); } } private void updateEditorListeners() { if (listenerManagers.isEmpty()) { removeAllEditorListeners(); return; } // Attach the performance-critical mouse move listener only if we really need it. if (lastKeyModifier == null || listenerManagers.get(lastKeyModifier.toString()) == null) { if (mouseMoveListenerRemover != null) { mouseMoveListenerRemover.remove(); mouseMoveListenerRemover = null; } } else { if (mouseMoveListenerRemover == null) { mouseMoveListenerRemover = editor.getBuffer().getMouseMoveListenerRegistrar().add(mouseListener); } } if (keyPressListenerRemover == null) { keyPressListenerRemover = editor.getKeyListenerRegistrar().add(keyPressListener); } if (nativeKeyUpListenerRemover == null) { nativeKeyUpListenerRemover = editor.getNativeKeyUpListenerRegistrar().add(keyUpListener); } /* * We should always listen to these events, since we want to release the * last key modifier upon receiving it. */ if (mouseOutListenerRemover == null) { mouseOutListenerRemover = editor.getBuffer().getMouseOutListenerRegistrar().add(mouseListener); } } private void removeAllEditorListeners() { if (keyPressListenerRemover != null) { keyPressListenerRemover.remove(); keyPressListenerRemover = null; } if (mouseMoveListenerRemover != null) { mouseMoveListenerRemover.remove(); mouseMoveListenerRemover = null; } if (mouseOutListenerRemover != null) { mouseOutListenerRemover.remove(); mouseOutListenerRemover = null; } if (nativeKeyUpListenerRemover != null) { nativeKeyUpListenerRemover.remove(); nativeKeyUpListenerRemover = null; } } private void handleOnMouseMove(final int x, final int y) { if (lastKeyModifier == null || editor.getDocument() == null) { return; } String key = lastKeyModifier.toString(); ListenerManager<MouseHoverListener> manager = listenerManagers.get(key); if (manager == null) { return; } int lineNumber = editor.getBuffer().convertYToLineNumber(y, true); final LineInfo lineInfo = editor.getDocument().getLineFinder().findLine(lineNumber); final int column = editor.getBuffer().convertXToRoundedVisibleColumn(x, lineInfo.line()); manager.dispatch(new ListenerManager.Dispatcher<MouseHoverListener>() { @Override public void dispatch(MouseHoverListener listener) { listener.onMouseHover(x, y, lineInfo, column); } }); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/ViewportModel.java
client/src/main/java/com/google/collide/client/editor/ViewportModel.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.MathUtils; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; /** * The model for the editor's viewport. This model also listens for events that * affect the viewport, and adjusts the bounds accordingly. For example, it * listens as a scroll listener and shifts the viewport when the user scrolls. * * The lifecycle of this class is tied to the current document in the editor. If * the document is replaced, a new instance of this class is used for the new * document. */ public class ViewportModel implements Buffer.ScrollListener, Buffer.ResizeListener, Document.LineListener, SelectionModel.CursorListener, Buffer.SpacerListener { private static final AnchorType VIEWPORT_MODEL_ANCHOR_TYPE = AnchorType.create( ViewportModel.class, "viewport model"); /** * Listener that is notified of viewport changes. */ public interface Listener { /** * Called when the content of the viewport changes, for example a line gets * added or removed. This will not be called if the text changes within a * line. * * @param added true if the given {@code lineInfo} was added, false if * removed (note that when removed, the lines will no longer be in * the document) * @param lines the lines added or removed (see the parameters on * {@link Document.LineListener}) */ void onViewportContentChanged(ViewportModel viewport, int lineNumber, boolean added, JsonArray<Line> lines); /** * Called when the viewport is shifted, meaning at least one of its edges * points to new lines. * * @param oldTop may be null if this is the first range set * @param oldBottom may be null if this is the first range set */ void onViewportShifted(ViewportModel viewport, LineInfo top, LineInfo bottom, LineInfo oldTop, LineInfo oldBottom); /** * Called when the line number of the viewport top or bottom changes. * * One example of where this differs from {@link #onViewportShifted} is if a * collaborator is typing above our viewport. When she presses ENTER, it our * viewport's line numbers will change, but will still point to the same * line instances. Therefore, this method would be called but not * {@link #onViewportShifted}. */ void onViewportLineNumberChanged(ViewportModel viewport, Edge edge); } public enum Edge { TOP, BOTTOM } private class ChangeDispatcher implements ListenerManager.Dispatcher<Listener> { private LineInfo oldTop; private LineInfo oldBottom; @Override public void dispatch(Listener listener) { listener.onViewportShifted(ViewportModel.this, topAnchor.getLineInfo(), bottomAnchor.getLineInfo(), oldTop, oldBottom); } private void dispatch(LineInfo oldTop, LineInfo oldBottom) { this.oldTop = oldTop; this.oldBottom = oldBottom; listenerManager.dispatch(this); } } static ViewportModel create(Document document, SelectionModel selection, Buffer buffer) { return new ViewportModel(document, selection, buffer); } private final Anchor.ShiftListener anchorShiftedListener = new Anchor.ShiftListener() { private final Dispatcher<Listener> lineNumberChangedDispatcher = new ListenerManager.Dispatcher<ViewportModel.Listener>() { @Override public void dispatch(Listener listener) { listener.onViewportLineNumberChanged(ViewportModel.this, curChangedEdge); } }; private Edge curChangedEdge; @Override public void onAnchorShifted(Anchor anchor) { curChangedEdge = anchor == topAnchor ? Edge.TOP : Edge.BOTTOM; listenerManager.dispatch(lineNumberChangedDispatcher); } }; private final AnchorManager anchorManager; private Anchor bottomAnchor; private final Buffer buffer; private final Document document; private final ChangeDispatcher changeDispatcher; private final ListenerManager<Listener> listenerManager; private final SelectionModel selection; private Anchor topAnchor; private final ListenerRegistrar.RemoverManager removerManager = new ListenerRegistrar.RemoverManager(); private ViewportModel(Document document, SelectionModel selection, Buffer buffer) { this.document = document; this.anchorManager = document.getAnchorManager(); this.buffer = buffer; this.changeDispatcher = new ChangeDispatcher(); this.listenerManager = ListenerManager.create(); this.selection = selection; attachHandlers(); } public LineInfo getBottom() { return bottomAnchor.getLineInfo(); } public Line getBottomLine() { return bottomAnchor.getLine(); } public int getBottomLineNumber() { return bottomAnchor.getLineNumber(); } public LineInfo getBottomLineInfo() { return bottomAnchor.getLineInfo(); } public Document getDocument() { return document; } public ListenerRegistrar<Listener> getListenerRegistrar() { return listenerManager; } public LineInfo getTop() { return topAnchor.getLineInfo(); } public Line getTopLine() { return topAnchor.getLine(); } public LineInfo getTopLineInfo() { return topAnchor.getLineInfo(); } public int getTopLineNumber() { return topAnchor.getLineNumber(); } public void initialize() { resetPosition(); } /** * Returns whether the text of the given {@code lineNumber} is fully visible * in the viewport, determined by the current scrollTop and height of the * buffer. * * Note: This does not check whether any spacers above the given line are * fully visible. */ public boolean isLineNumberFullyVisibleInViewport(int lineNumber) { int lineTop = buffer.calculateLineTop(lineNumber); int scrollTop = buffer.getScrollTop(); int lineHeight = buffer.getEditorLineHeight(); return lineTop >= scrollTop && (lineTop + lineHeight) <= scrollTop + buffer.getHeight(); } public boolean isLineInViewport(Line line) { // Lines in the viewport will always return a line number int lineNumber = LineUtils.getCachedLineNumber(line); return (lineNumber != -1) && isLineNumberInViewport(lineNumber); } public boolean isLineNumberInViewport(int lineNumber) { /* * TODO: fix this to only do the expensive * calculation when a spacer is in the viewport. */ /* * When the viewport is covered entirely by a spacer, the lines set as top * and bottom aren't actually visible, so check using their absolute buffer * positions. */ int bufferTop = buffer.getScrollTop(); int bufferBottom = bufferTop + buffer.getHeight(); int lineTop = buffer.calculateLineTop(lineNumber); int lineBottom = lineTop + buffer.getEditorLineHeight(); return !(bufferTop > lineBottom || bufferBottom < lineTop); } @Override public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) { int cursorLineNumber = lineInfo.number(); int cursorLeft = buffer.calculateColumnLeft(lineInfo.line(), column); int cursorTop = buffer.calculateLineTop(cursorLineNumber); int scrollLeft = buffer.getScrollLeft(); int scrollTop = buffer.getScrollTop(); int newScrollLeft = scrollLeft; int newScrollTop = scrollTop; int lineHeight = buffer.getEditorLineHeight(); int bufferHeight = buffer.getHeight(); int preCursorLineTop = Math.max(cursorTop - lineHeight, 0); int postCursorLineBottom = cursorTop + 2 * lineHeight; if (preCursorLineTop < scrollTop) { newScrollTop = preCursorLineTop; } else { if (postCursorLineBottom > scrollTop + bufferHeight) { newScrollTop = postCursorLineBottom - bufferHeight; } } if (cursorLeft < scrollLeft) { newScrollLeft = cursorLeft; } else { int bufferWidth = buffer.getWidth(); int columnWidth = (int) buffer.getEditorCharacterWidth(); if (cursorLeft + columnWidth > scrollLeft + bufferWidth) { newScrollLeft = cursorLeft + columnWidth - bufferWidth; } } if (newScrollTop != scrollTop || newScrollLeft != scrollLeft) { setBufferScrollAsync(newScrollLeft, newScrollTop); } } @Override public void onLineAdded(Document document, final int lineNumber, final JsonArray<Line> addedLines) { if (adjustViewportBoundsForLineAdditionOrRemoval(document, lineNumber)) { listenerManager.dispatch(new Dispatcher<ViewportModel.Listener>() { @Override public void dispatch(Listener listener) { listener.onViewportContentChanged(ViewportModel.this, lineNumber, true, addedLines); } }); } } @Override public void onLineRemoved(Document document, final int lineNumber, final JsonArray<Line> removedLines) { if (adjustViewportBoundsForLineAdditionOrRemoval(document, lineNumber)) { listenerManager.dispatch(new Dispatcher<ViewportModel.Listener>() { @Override public void dispatch(Listener listener) { listener.onViewportContentChanged(ViewportModel.this, lineNumber, false, removedLines); } }); } } @Override public void onScroll(Buffer buffer, int scrollTop) { moveViewportToScrollTop(scrollTop); } @Override public void onResize(Buffer buffer, int documentHeight, int viewportHeight, int scrollTop) { moveViewportToScrollTop(scrollTop); } private void moveViewportToScrollTop(int scrollTop) { int newTopLineNumber = buffer.convertYToLineNumber(scrollTop, true); int numLinesToShow = buffer.getFlooredHeightInLines() + 1; moveViewportToLineNumber(newTopLineNumber, numLinesToShow); } public void teardown() { removeAnchors(); detachHandlers(); } /** * Adjusts the viewport bounds after a line is added or removed, returning * whether there an adjustment was made. */ private boolean adjustViewportBoundsForLineAdditionOrRemoval(Document document, int lineNumber) { int bottomLineNumber = bottomAnchor.getLineNumber(); int topLineNumber = topAnchor.getLineNumber(); int lastVisibleLineNumber = topLineNumber + buffer.getFlooredHeightInLines(); /* * The "lastVisibleLineNumber != bottomLineNumber" catches the case where * the viewport's last line is deleted, causing the bottom anchor to shift * up a line before this method is called. So, the lineNumber will not be in * the range of the top and bottom anchors. */ if (MathUtils.isInRangeInclusive(lineNumber, topLineNumber, bottomLineNumber) || lastVisibleLineNumber != bottomLineNumber) { // Update the viewport to cope with the line addition or removal int shiftAmount = lastVisibleLineNumber - bottomLineNumber; if (shiftAmount != 0) { shiftBottomAnchor(shiftAmount); } return true; } else { return false; } } private void attachHandlers() { removerManager.track(buffer.getScrollListenerRegistrar().add(this)); removerManager.track(buffer.getResizeListenerRegistrar().add(this)); removerManager.track(document.getLineListenerRegistrar().add(this)); removerManager.track(selection.getCursorListenerRegistrar().add(this)); removerManager.track(buffer.getSpacerListenerRegistrar().add(this)); } private void detachHandlers() { removerManager.remove(); } private void moveViewportToLineNumber(int topLineNumber, int numLinesToShow) { LineFinder lineFinder = buffer.getDocument().getLineFinder(); LineInfo newTop = lineFinder.findLine(getTop(), topLineNumber); int targetBottomLineNumber = newTop.number() + numLinesToShow - 1; LineInfo newBottom = lineFinder.findLine(getBottom(), Math.min(document.getLastLineNumber(), targetBottomLineNumber)); setRange(newTop, newBottom); } public void shiftHorizontally(boolean right) { int deltaScrollLeft = right ? 20 : -20; setBufferScrollAsync(buffer.getScrollLeft() + deltaScrollLeft, buffer.getScrollTop()); } public void shiftVertically(boolean down, boolean byPage) { int deltaAbsoluteScrollTop = byPage ? buffer.getHeight() - buffer.getEditorLineHeight() : buffer.getEditorLineHeight(); int deltaScrollTop = down ? deltaAbsoluteScrollTop : -deltaAbsoluteScrollTop; setBufferScrollAsync(buffer.getScrollLeft(), buffer.getScrollTop() + deltaScrollTop); } public void jumpTo(boolean end) { int newScrollTop = end ? buffer.getScrollHeight() - buffer.getHeight() : 0; setBufferScrollAsync(buffer.getScrollLeft(), newScrollTop); } private void removeAnchors() { anchorManager.removeAnchor(topAnchor); anchorManager.removeAnchor(bottomAnchor); topAnchor = null; bottomAnchor = null; } private void resetPosition() { LineInfo firstLine = new LineInfo(document.getFirstLine(), 0); int lastLineNumber = Math.min(document.getLastLineNumber(), buffer.getFlooredHeightInLines()); LineInfo lastLine = document.getLineFinder().findLine(lastLineNumber); setRange(firstLine, lastLine); } /** * Sets scroll top of the buffer asynchronously. This allows some events to be * processed in the browser event loop between renders. (For example, without * the asynchronous posting, holding down page down would only render one * frame a second.) */ private void setBufferScrollAsync(final int scrollLeft, final int scrollTop) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { buffer.setScrollLeft(Math.max(0, scrollLeft)); /* We'll synchronously get a callback and shift our viewport model to this new scroll top */ buffer.setScrollTop(Math.max(0, scrollTop)); } }); } private void setRange(LineInfo newTop, LineInfo newBottom) { LineInfo oldTop; LineInfo oldBottom; if (topAnchor == null || bottomAnchor == null) { oldTop = oldBottom = null; topAnchor = anchorManager.createAnchor(VIEWPORT_MODEL_ANCHOR_TYPE, newTop.line(), newTop.number(), AnchorManager.IGNORE_COLUMN); topAnchor.setRemovalStrategy(RemovalStrategy.SHIFT); topAnchor.getShiftListenerRegistrar().add(anchorShiftedListener); bottomAnchor = anchorManager.createAnchor(VIEWPORT_MODEL_ANCHOR_TYPE, newBottom.line(), newBottom.number(), AnchorManager.IGNORE_COLUMN); bottomAnchor.setRemovalStrategy(RemovalStrategy.SHIFT); bottomAnchor.getShiftListenerRegistrar().add(anchorShiftedListener); } else { oldTop = topAnchor.getLineInfo(); oldBottom = bottomAnchor.getLineInfo(); if (oldTop.equals(newTop) && oldBottom.equals(newBottom)) { return; } anchorManager.moveAnchor(topAnchor, newTop.line(), newTop.number(), AnchorManager.IGNORE_COLUMN); anchorManager.moveAnchor(bottomAnchor, newBottom.line(), newBottom.number(), AnchorManager.IGNORE_COLUMN); } changeDispatcher.dispatch(oldTop, oldBottom); } /** * @param lineCount if negative, the bottom anchor will shift upward that many * lines */ private void shiftBottomAnchor(int lineCount) { LineInfo bottomLineInfo = bottomAnchor.getLineInfo(); if (lineCount < 0) { for (; lineCount < 0; lineCount++) { bottomLineInfo.moveToPrevious(); } } else { for (; lineCount > 0; lineCount--) { bottomLineInfo.moveToNext(); } } setRange(topAnchor.getLineInfo(), bottomLineInfo); } @Override public void onSpacerAdded(Spacer spacer) { updateBoundsAfterSpacerChanged(spacer.getLineNumber()); } @Override public void onSpacerHeightChanged(Spacer spacer, int oldHeight) { updateBoundsAfterSpacerChanged(spacer.getLineNumber()); } @Override public void onSpacerRemoved(Spacer spacer, Line oldLine, int oldLineNumber) { updateBoundsAfterSpacerChanged(oldLineNumber); } private void updateBoundsAfterSpacerChanged(int spacerLineNumber) { if (spacerLineNumber < getTopLineNumber() || spacerLineNumber > getBottomLineNumber()) { return; } int newBottomLineNumber = buffer.convertYToLineNumber(buffer.getScrollTop() + buffer.getHeight(), true); setRange(getTop(), document .getLineFinder().findLine(getBottom(), newBottomLineNumber)); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/EditorActivityManager.java
client/src/main/java/com/google/collide/client/editor/EditorActivityManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.Buffer.ScrollListener; import com.google.collide.client.editor.Editor.KeyListener; import com.google.collide.client.util.UserActivityManager; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.ListenerRegistrar.Remover; /** * A class that listens to editor events to update the user activity manager on * the user's status. * */ public class EditorActivityManager { private JsonArray<Remover> listenerRemovers = JsonCollections.createArray(); EditorActivityManager(final UserActivityManager userActivityManager, ListenerRegistrar<ScrollListener> scrollListenerRegistrar, ListenerRegistrar<KeyListener> keyListenerRegistrar) { listenerRemovers.add(scrollListenerRegistrar.add(new ScrollListener() { @Override public void onScroll(Buffer buffer, int scrollTop) { userActivityManager.markUserActive(); } })); listenerRemovers.add(keyListenerRegistrar.add(new KeyListener() { @Override public boolean onKeyPress(SignalEvent event) { userActivityManager.markUserActive(); return false; } })); } void teardown() { for (int i = 0, n = listenerRemovers.size(); i < n; i++) { listenerRemovers.get(i).remove(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/LineRenderer.java
client/src/main/java/com/google/collide/client/editor/renderer/LineRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import javax.annotation.Nullable; import com.google.collide.shared.document.Line; /** * An interface for a renderer that renders a line at a time. */ public interface LineRenderer { /** * Receives the style to render the next {@code characterCount} characters. * This is how the renderer "renders". */ public interface Target { void render(int characterCount, @Nullable String styleName); } /** * Called when the LineRenderer should render its next chunk by calling * {@link Target#render(int, String)} on {@code target}. */ void renderNextChunk(Target target); /** * Called when a line is about to be rendered. * * @return true if this LineRenderer wants to participate in the rendering of * this line */ boolean resetToBeginningOfLine(Line line, int lineNumber); /** * @return true if last chunk (\n character) style should fill to right until * visible end of the editor line */ boolean shouldLastChunkFillToRight(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/SingleChunkLineRenderer.java
client/src/main/java/com/google/collide/client/editor/renderer/SingleChunkLineRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.anchor.Anchor; /** * Implements a {@link LineRenderer} that wraps a given area in the document * with an element with the given class name. */ public abstract class SingleChunkLineRenderer implements LineRenderer { /** * Creates a new renderer using line/column numbers (prone to collaboration * issues). * * @param startLine the first line to render * @param startColumn the first column to render * @param endLine the last line to render (inclusive) * @param endColumn the last column to render (inclusive) * @param className the CSS class to apply */ public static SingleChunkLineRenderer create(final int startLine, final int startColumn, final int endLine, final int endColumn, String className) { return new SingleChunkLineRenderer(className) { @Override public int startLine() { return startLine; } @Override public int startColumn() { return startColumn; } @Override public int endLine() { return endLine; } @Override public int endColumn() { return endColumn; } }; } /** * Creates a new renderer using anchors. * * @param startAnchor the rendering start point. * @param endAnchor the last part to render (note that whatever line or * character the anchor is at will also be rendered. * @param className the CSS class name to apply */ public static SingleChunkLineRenderer create(final Anchor startAnchor, final Anchor endAnchor, String className) { return new SingleChunkLineRenderer(className) { @Override public int startLine() { return startAnchor.getLineNumber(); } @Override public int startColumn() { return startAnchor.getColumn(); } @Override public int endLine() { return endAnchor.getLineNumber(); } @Override public int endColumn() { return endAnchor.getColumn(); } }; } private final String className; private int currentLineNumber; private int currentLineLength; private int linePosition; private SingleChunkLineRenderer(String className) { this.className = className; } public abstract int startLine(); public abstract int startColumn(); public abstract int endLine(); public abstract int endColumn(); @Override public void renderNextChunk(Target target) { if (currentLineNumber < startLine() || currentLineNumber > endLine()) { // Out of the chunk to be rendered. render(target, currentLineLength - linePosition, null); } else if (currentLineNumber == startLine() && linePosition < startColumn()) { // Still out of the chunk to be rendered. render(target, startColumn() - linePosition, null); } else if (currentLineNumber == endLine() && linePosition > endColumn()) { // Right after the chunk was rendered. render(target, currentLineLength - linePosition, null); } else if (currentLineNumber == endLine()) { // Chunk ends at the current line. render(target, endColumn() + 1 - linePosition, className); } else { // The rest of the line belongs to the chunk. render(target, currentLineLength - linePosition, className); } } private void render(LineRenderer.Target target, int characterCount, String styleName) { target.render(characterCount, styleName); linePosition += characterCount; } @Override public boolean resetToBeginningOfLine(Line line, int lineNumber) { if (lineNumber < startLine() || lineNumber > endLine()) { return false; } this.currentLineNumber = lineNumber; this.currentLineLength = line.getText().length(); this.linePosition = 0; return true; } @Override public boolean shouldLastChunkFillToRight() { return false; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/Renderer.java
client/src/main/java/com/google/collide/client/editor/renderer/Renderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import java.util.EnumSet; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.FocusManager; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.gutter.Gutter; import com.google.collide.client.editor.renderer.ChangeTracker.ChangeType; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.logging.Log; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerRegistrar; /** * A class that is the entry point for the rendering of the editor. * * The lifecycle of this class is tied to the current document. If the document * is replaced, a new instance of this class is created for the new document. * */ public class Renderer { public static Renderer create(Document document, ViewportModel viewport, Buffer buffer, Gutter leftGutter, SelectionModel selection, FocusManager focusManager, Editor editor, LineNumberRenderer.Resources res, RenderTimeExecutor renderTimeExecutor) { return new Renderer(document, viewport, buffer, leftGutter, selection, focusManager, editor, res, renderTimeExecutor); } /** * Listener that is notified when the rendering is finished. */ public interface CompletionListener { void onRenderCompleted(); } /** * Listener that is notified on creation and garbage collection of a * rendered line. */ public interface LineLifecycleListener { void onRenderedLineCreated(Line line, int lineNumber); void onRenderedLineGarbageCollected(Line line); void onRenderedLineShifted(Line line, int lineNumber); } private static final boolean ENABLE_PROFILING = false; private final ChangeTracker changeTracker; private final ListenerManager<CompletionListener> completionListenerManager; private final ListenerManager<LineLifecycleListener> lineLifecycleListenerManager; private final LineNumberRenderer lineNumberRenderer; private final ListenerManager.Dispatcher<CompletionListener> renderCompletedDispatcher = new ListenerManager.Dispatcher<CompletionListener>() { @Override public void dispatch(CompletionListener listener) { listener.onRenderCompleted(); } }; private final ViewportRenderer viewportRenderer; private final ViewportModel viewport; private final RenderTimeExecutor renderTimeExecutor; private Renderer(Document document, ViewportModel viewport, Buffer buffer, Gutter leftGutter, SelectionModel selection, FocusManager focusManager, Editor editor, LineNumberRenderer.Resources res, RenderTimeExecutor renderTimeExecutor) { this.viewport = viewport; this.renderTimeExecutor = renderTimeExecutor; this.completionListenerManager = ListenerManager.create(); this.lineLifecycleListenerManager = ListenerManager.create(); this.changeTracker = new ChangeTracker(this, buffer, document, viewport, selection, focusManager); this.viewportRenderer = new ViewportRenderer( document, buffer, viewport, editor.getView(), lineLifecycleListenerManager); this.lineNumberRenderer = new LineNumberRenderer(buffer, res, leftGutter, viewport, selection, editor); } public void addLineRenderer(LineRenderer lineRenderer) { viewportRenderer.addLineRenderer(lineRenderer); } public ListenerRegistrar<CompletionListener> getCompletionListenerRegistrar() { return completionListenerManager; } public ListenerRegistrar<LineLifecycleListener> getLineLifecycleListenerRegistrar() { return lineLifecycleListenerManager; } public void removeLineRenderer(LineRenderer lineRenderer) { viewportRenderer.removeLineRenderer(lineRenderer); } public void renderAll() { viewportRenderer.render(); renderTimeExecutor.executeQueuedCommands(); handleRenderCompleted(); } public void renderChanges() { if (ENABLE_PROFILING) { Log.markTimeline(getClass(), "Rendering changes..."); } EnumSet<ChangeType> changes = changeTracker.getChanges(); int viewportTopmostContentChangedLine = Math.max(viewport.getTopLineNumber(), changeTracker.getTopmostContentChangedLineNumber()); if (changes.contains(ChangeType.VIEWPORT_LINE_NUMBER)) { if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - lineNumberRenderer..."); } lineNumberRenderer.render(); if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - renderViewportLineNumbersChanged..."); } viewportRenderer.renderViewportLineNumbersChanged(changeTracker .getViewportLineNumberChangedEdges()); } if (changes.contains(ChangeType.VIEWPORT_CONTENT)) { if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - renderViewportContentChange..."); } viewportRenderer.renderViewportContentChange(viewportTopmostContentChangedLine, changeTracker.getViewportRemovedLines()); if (changeTracker.hadContentChangeThatUpdatesFollowingLines()) { if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - renderLineAndFollowing..."); } lineNumberRenderer.renderLineAndFollowing(viewportTopmostContentChangedLine); } } if (changes.contains(ChangeType.VIEWPORT_SHIFT)) { if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - renderViewportShift..."); } viewportRenderer.renderViewportShift(false); lineNumberRenderer.render(); } if (changes.contains(ChangeType.DIRTY_LINE)) { if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - renderDirtyLines..."); } viewportRenderer.renderDirtyLines(changeTracker.getDirtyLines()); } renderTimeExecutor.executeQueuedCommands(); handleRenderCompleted(); if (ENABLE_PROFILING) { Log.markTimeline(getClass(), " - Done rendering changes"); } } private void handleRenderCompleted() { viewportRenderer.handleRenderCompleted(); completionListenerManager.dispatch(renderCompletedDispatcher); } public void requestRenderLine(Line line) { changeTracker.requestRenderLine(line); } public void teardown() { changeTracker.teardown(); viewportRenderer.teardown(); lineNumberRenderer.teardown(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/LineNumberRenderer.java
client/src/main/java/com/google/collide/client/editor/renderer/LineNumberRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import collide.client.util.Elements; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.gutter.Gutter; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.JsIntegerMap; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; import com.google.gwt.resources.client.ClientBundle; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; /** * A renderer for the line numbers in the left gutter. */ public class LineNumberRenderer { private static final int NONE = -1; private final Buffer buffer; private final Gutter leftGutter; /** * Current editor instance. * * Used to track if current fie can be edited (i.e. is not readonly). * * TODO: add new abstraction to avoid editor passing. */ private final Editor editor; private int previousBottomLineNumber = -1; private int previousTopLineNumber = -1; private JsIntegerMap<Element> lineNumberToElementCache; private final ViewportModel viewport; private final Css css; private int activeLineNumber = NONE; private int renderedActiveLineNumber = NONE; private final JsonArray<ListenerRegistrar.Remover> listenerRemovers = JsonCollections.createArray(); private final SelectionModel.CursorListener cursorListener = new SelectionModel.CursorListener() { @Override public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) { activeLineNumber = lineInfo.number(); updateActiveLine(); } }; private Editor.ReadOnlyListener readonlyListener = new Editor.ReadOnlyListener() { @Override public void onReadOnlyChanged(boolean isReadOnly) { updateActiveLine(); } }; private void updateActiveLine() { int lineNumber = this.activeLineNumber; if (editor.isReadOnly()) { lineNumber = NONE; } if (lineNumber == renderedActiveLineNumber) { return; } if (renderedActiveLineNumber != NONE) { Element renderedActiveLine = lineNumberToElementCache.get(renderedActiveLineNumber); if (renderedActiveLine != null) { renderedActiveLine.removeClassName(css.activeLineNumber()); renderedActiveLineNumber = NONE; } } Element newActiveLine = lineNumberToElementCache.get(lineNumber); // Add class if it's in the viewport. if (newActiveLine != null) { newActiveLine.addClassName(css.activeLineNumber()); renderedActiveLineNumber = lineNumber; } } public void teardown() { for (int i = 0, n = listenerRemovers.size(); i < n; i++) { listenerRemovers.get(i).remove(); } } /** * Line number CSS. */ public interface Css extends Editor.EditorSharedCss { String lineNumber(); String activeLineNumber(); } /** * Line number resources. */ public interface Resources extends ClientBundle { @Source({"collide/client/common/constants.css", "LineNumberRenderer.css"}) Css lineNumberRendererCss(); } LineNumberRenderer(Buffer buffer, Resources res, Gutter leftGutter, ViewportModel viewport, SelectionModel selection, Editor editor) { this.buffer = buffer; this.leftGutter = leftGutter; this.editor = editor; this.lineNumberToElementCache = JsIntegerMap.create(); this.viewport = viewport; this.css = res.lineNumberRendererCss(); listenerRemovers.add(selection.getCursorListenerRegistrar().add(cursorListener)); listenerRemovers.add(editor.getReadOnlyListenerRegistrar().add(readonlyListener)); } void renderImpl(int updateBeginLineNumber) { int topLineNumber = viewport.getTopLineNumber(); int bottomLineNumber = viewport.getBottomLineNumber(); if (previousBottomLineNumber == -1 || topLineNumber > previousBottomLineNumber || bottomLineNumber < previousTopLineNumber) { if (previousBottomLineNumber > -1) { garbageCollectLines(previousTopLineNumber, previousBottomLineNumber); } fillOrUpdateLines(topLineNumber, bottomLineNumber); } else { /* * The viewport was shifted and part of the old viewport will be in the * new viewport. */ // first garbage collect any lines that have gone off the screen if (previousTopLineNumber < topLineNumber) { // off the top garbageCollectLines(previousTopLineNumber, topLineNumber - 1); } if (previousBottomLineNumber > bottomLineNumber) { // off the bottom garbageCollectLines(bottomLineNumber + 1, previousBottomLineNumber); } /* * Re-create any line numbers that are now visible or have had their * positions shifted. */ if (previousTopLineNumber > topLineNumber) { // new lines at the top fillOrUpdateLines(topLineNumber, previousTopLineNumber - 1); } if (updateBeginLineNumber >= 0 && updateBeginLineNumber <= bottomLineNumber) { // lines updated in the middle; redraw everything below fillOrUpdateLines(updateBeginLineNumber, bottomLineNumber); } else { // only check new lines scrolled in from the bottom if (previousBottomLineNumber < bottomLineNumber) { fillOrUpdateLines(previousBottomLineNumber, bottomLineNumber); } } } previousTopLineNumber = viewport.getTopLineNumber(); previousBottomLineNumber = viewport.getBottomLineNumber(); } void render() { renderImpl(-1); } /** * Re-render all line numbers including and after lineNumber to account for * spacer movement. */ void renderLineAndFollowing(int lineNumber) { renderImpl(lineNumber); } private void fillOrUpdateLines(int beginLineNumber, int endLineNumber) { for (int i = beginLineNumber; i <= endLineNumber; i++) { Element lineElement = lineNumberToElementCache.get(i); if (lineElement != null) { updateElementPosition(lineElement, i); } else { Element element = createElement(i); lineNumberToElementCache.put(i, element); leftGutter.addUnmanagedElement(element); } } } private void updateElementPosition(Element lineNumberElement, int lineNumber) { lineNumberElement.getStyle().setTop( buffer.calculateLineTop(lineNumber), CSSStyleDeclaration.Unit.PX); } private Element createElement(int lineNumber) { Element element = Elements.createDivElement(css.lineNumber()); // Line 0 will be rendered as Line 1 element.setTextContent(String.valueOf(lineNumber + 1)); element.getStyle().setTop(buffer.calculateLineTop(lineNumber), CSSStyleDeclaration.Unit.PX); if (lineNumber == activeLineNumber) { element.addClassName(css.activeLineNumber()); renderedActiveLineNumber = activeLineNumber; } return element; } private void garbageCollectLines(int beginLineNumber, int endLineNumber) { for (int i = beginLineNumber; i <= endLineNumber; i++) { Element lineElement = lineNumberToElementCache.get(i); if (lineElement != null) { leftGutter.removeUnmanagedElement(lineElement); lineNumberToElementCache.erase(i); } else { throw new IndexOutOfBoundsException( "Tried to garbage collect line number " + i + " when it does not exist."); } } if (beginLineNumber <= renderedActiveLineNumber && renderedActiveLineNumber <= endLineNumber) { renderedActiveLineNumber = NONE; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/LineRendererController.java
client/src/main/java/com/google/collide/client/editor/renderer/LineRendererController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import collide.client.util.Elements; import com.google.collide.client.document.linedimensions.LineDimensionsUtils; import com.google.collide.client.editor.Buffer; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.SortedList; import com.google.collide.shared.util.StringUtils; import com.google.common.base.Preconditions; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.html.SpanElement; /** * A class to maintain the list of {@link LineRenderer LineRenderers} and render * a line by delegating to each of the renderers. */ class LineRendererController { /* * TODO: consider recycling these if GC performance during * rendering is an issue */ private static class LineRendererTarget implements LineRenderer.Target { private static class Comparator implements SortedList.Comparator<LineRendererTarget> { @Override public int compare(LineRendererTarget a, LineRendererTarget b) { return a.remainingCount - b.remainingCount; } } /** The line renderer for which this is the target */ private final LineRenderer lineRenderer; /** * The remaining number of characters that should receive {@link #styleName} * . Once this is 0, the {@link #lineRenderer} will be asked to render its * next chunk */ private int remainingCount; /** The style to be applied to the {@link #remainingCount} */ private String styleName; public LineRendererTarget(LineRenderer lineRenderer) { this.lineRenderer = lineRenderer; } @Override public void render(int characterCount, String styleName) { remainingCount = characterCount; this.styleName = styleName; } } /** * A sorted list storing targets for the line renderers that are participating * in rendering the current line */ private final SortedList<LineRendererTarget> currentLineRendererTargets; /** * A list of all of the line renderers that are registered on the editor (Note * that some may not be participating in the current line) */ private final JsonArray<LineRenderer> lineRenderers; private final Buffer buffer; LineRendererController(Buffer buffer) { this.buffer = buffer; currentLineRendererTargets = new SortedList<LineRendererController.LineRendererTarget>( new LineRendererTarget.Comparator()); lineRenderers = JsonCollections.createArray(); } void addLineRenderer(LineRenderer lineRenderer) { if (!lineRenderers.contains(lineRenderer)) { /* * Prevent line renderer from appearing twice in the list if it is already * added. */ lineRenderers.add(lineRenderer); } } void removeLineRenderer(LineRenderer lineRenderer) { lineRenderers.remove(lineRenderer); } void renderLine(Line line, int lineNumber, Element targetElement, boolean isTargetElementEmpty) { currentLineRendererTargets.clear(); if (!resetLineRenderers(line, lineNumber)) { // No line renderers are participating, so exit early. setTextContentSafely(targetElement, line.getText()); return; } if (!isTargetElementEmpty) { targetElement.setInnerHTML(""); } Element contentElement = Elements.createSpanElement(); contentElement.getStyle().setDisplay(CSSStyleDeclaration.Display.INLINE_BLOCK); for (int indexInLine = 0, lineSize = line.getText().length(); indexInLine < lineSize && ensureAllRenderersHaveARenderedNextChunk();) { int chunkSize = currentLineRendererTargets.get(0).remainingCount; if (chunkSize == 0) { // Bad news, revert to naive rendering and log setTextContentSafely(targetElement, line.getText()); Log.error(getClass(), "Line renderers do not have remaining chunks"); return; } renderChunk(line.getText(), indexInLine, chunkSize, contentElement); markChunkRendered(chunkSize); indexInLine += chunkSize; } targetElement.appendChild(contentElement); if (line.getText().endsWith("\n")) { Element lastChunk = (Element) contentElement.getLastChild(); Preconditions.checkState(lastChunk != null, "This line has no chunks!"); if (!StringUtils.isNullOrWhitespace(lastChunk.getClassName())) { contentElement.getStyle().setProperty("float", "left"); Element newlineCharacterElement = createLastChunkElement(targetElement); // Created on demand only because it is rarely used. Element remainingSpaceElement = null; for (int i = 0, n = currentLineRendererTargets.size(); i < n; i++) { LineRendererTarget target = currentLineRendererTargets.get(i); if (target.styleName != null) { if (!target.lineRenderer.shouldLastChunkFillToRight()) { newlineCharacterElement.addClassName(target.styleName); } else { if (remainingSpaceElement == null) { newlineCharacterElement.getStyle().setProperty("float", "left"); remainingSpaceElement = createLastChunkElement(targetElement); remainingSpaceElement.getStyle().setWidth("100%"); } // Also apply to last chunk element so that there's no gap. newlineCharacterElement.addClassName(target.styleName); remainingSpaceElement.addClassName(target.styleName); } } } } } } private static Element createLastChunkElement(Element parent) { // we need to give them a whitespace element so that it can be styled. Element whitespaceElement = Elements.createSpanElement(); whitespaceElement.setTextContent("\u00A0"); whitespaceElement.getStyle().setDisplay("inline-block"); parent.appendChild(whitespaceElement); return whitespaceElement; } /** * Ensures all renderer targets (that want to render) have rendered each of * their next chunks. */ private boolean ensureAllRenderersHaveARenderedNextChunk() { while (currentLineRendererTargets.size() > 0 && currentLineRendererTargets.get(0).remainingCount == 0) { LineRendererTarget target = currentLineRendererTargets.get(0); try { target.lineRenderer.renderNextChunk(target); } catch (Throwable t) { // Cause naive rendering target.remainingCount = 0; Log.warn(getClass(), "An exception was thrown from renderNextChunk", t); } if (target.remainingCount > 0) { currentLineRendererTargets.repositionItem(0); } else { // Remove the line renderer because it has broken our contract currentLineRendererTargets.remove(0); Log.warn(getClass(), "The line renderer " + target.lineRenderer + " is lacking a next chunk, removing from rendering"); } } return currentLineRendererTargets.size() > 0; } /** * Marks the chunk rendered on all the renderers. */ private void markChunkRendered(int chunkSize) { for (int i = 0, n = currentLineRendererTargets.size(); i < n; i++) { LineRendererTarget target = currentLineRendererTargets.get(i); target.remainingCount -= chunkSize; } } /** * Renders the chunk by creating a span with all of the individual line * renderer's styles. */ private void renderChunk(String lineText, int lineIndex, int chunkLength, Element targetElement) { SpanElement element = Elements.createSpanElement(); // TODO: file a Chrome bug, place link here element.getStyle().setDisplay(CSSStyleDeclaration.Display.INLINE_BLOCK); setTextContentSafely(element, lineText.substring(lineIndex, lineIndex + chunkLength)); applyStyles(element); targetElement.appendChild(element); } private void applyStyles(Element element) { for (int i = 0, n = currentLineRendererTargets.size(); i < n; i++) { LineRendererTarget target = currentLineRendererTargets.get(i); if (target.styleName != null) { element.addClassName(target.styleName); } } } /** * Resets the line renderers, preparing for a new line to be rendered. * * This method fills the {@link #currentLineRendererTargets} with targets for * line renderers that will participate in rendering this line. * * @return true if there is at least one line renderer participating for the * given @{link Line} line. */ private boolean resetLineRenderers(Line line, int lineNumber) { boolean hasAtLeastOneParticipatingLineRenderer = false; for (int i = 0; i < lineRenderers.size(); i++) { LineRenderer lineRenderer = lineRenderers.get(i); boolean isParticipating = lineRenderer.resetToBeginningOfLine(line, lineNumber); if (isParticipating) { currentLineRendererTargets.add(new LineRendererTarget(lineRenderer)); hasAtLeastOneParticipatingLineRenderer = true; } } return hasAtLeastOneParticipatingLineRenderer; } private void setTextContentSafely(Element element, String text) { String cleansedText = text.replaceAll("\t", LineDimensionsUtils.getTabAsSpaces()); element.setTextContent(cleansedText); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/RenderTimeExecutor.java
client/src/main/java/com/google/collide/client/editor/renderer/RenderTimeExecutor.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import com.google.collide.client.util.Executor; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * An executor that will defer the commands given to {@link #execute(Runnable)} * until render-time. * */ public class RenderTimeExecutor implements Executor { private final JsonArray<Runnable> commands = JsonCollections.createArray(); @Override public void execute(Runnable command) { commands.add(command); } void executeQueuedCommands() { for (int i = 0, n = commands.size(); i < n; i++) { commands.get(i).run(); } commands.clear(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/PreviousAnchorRenderer.java
client/src/main/java/com/google/collide/client/editor/renderer/PreviousAnchorRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; /** * A line based renderer strategy that uses anchors to define chunk boundaries. * * At any given point in the document, the previous anchor of the given type * contains the information necessary to calculate the style of the current * chunk. */ public class PreviousAnchorRenderer implements LineRenderer { /** * Calculate the style to use for the given previous anchor. */ public interface AnchorStyleGetter { public String getStyle(Anchor previousAnchor); } /** * Default style getter which simply uses the anchor's value as the style. */ private static class AnchorValueIsStyle implements AnchorStyleGetter { @Override public String getStyle(Anchor previousAnchor) { return previousAnchor.getValue(); } } public static final AnchorStyleGetter ANCHOR_VALUE_IS_STYLE = new AnchorValueIsStyle(); /** * The render anchor is a positional anchor used to search backwards for the * previous diffchunk. */ private static final AnchorType START_SEARCH_ANCHOR_TYPE = AnchorType.create(PreviousAnchorRenderer.class, "start"); protected final Document document; private final AnchorType anchorType; private final AnchorStyleGetter styleGetter; private int nextChunkLength = 0; private int linePosition = 0; private Line line; private Anchor prevAnchor = null; public PreviousAnchorRenderer( Document document, AnchorType anchorType, AnchorStyleGetter styleGetter) { this.document = document; this.anchorType = anchorType; this.styleGetter = styleGetter; } @Override public void renderNextChunk(Target target) { assert (prevAnchor != null); assert (nextChunkLength > 0); String chunkStyle = styleGetter.getStyle(prevAnchor); target.render(nextChunkLength, chunkStyle); linePosition += nextChunkLength; if (linePosition < line.getText().length()) { calculateNextChunk(); } } @Override public boolean resetToBeginningOfLine(Line line, int lineNumber) { // Reset the line rendering state this.line = line; linePosition = 0; nextChunkLength = 0; prevAnchor = null; calculateNextChunk(); return nextChunkLength > 0; } @Override public boolean shouldLastChunkFillToRight() { return false; } /** * Using the current rendering state, calculate the length and style for the * next diff chunk. */ private void calculateNextChunk() { // Get the previous anchor for this line AnchorManager anchorManager = document.getAnchorManager(); if (prevAnchor == null) { Anchor startSearchAnchor = document.getAnchorManager().createAnchor( START_SEARCH_ANCHOR_TYPE, line, AnchorManager.IGNORE_LINE_NUMBER, 1); prevAnchor = document.getAnchorManager().getPreviousAnchor(startSearchAnchor, anchorType); document.getAnchorManager().removeAnchor(startSearchAnchor); if (prevAnchor == null) { return; } } else { // We have hit an anchor on this line already, get the next one. prevAnchor = anchorManager.getNextAnchor(prevAnchor, anchorType); } Anchor nextAnchor = anchorManager.getNextAnchor(prevAnchor, anchorType); if (nextAnchor != null && nextAnchor.getLine() == line) { nextChunkLength = nextAnchor.getColumn() - linePosition; } else { nextChunkLength = line.getText().length() - linePosition; } assert (nextChunkLength >= 0) : "Got a negative chunk length"; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/ChangeTracker.java
client/src/main/java/com/google/collide/client/editor/renderer/ChangeTracker.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import java.util.EnumSet; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.FocusManager; import com.google.collide.client.editor.Spacer; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.ViewportModel.Edge; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.ScheduledCommandExecutor; import com.google.collide.client.util.logging.Log; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.document.util.LineUtils.LineVisitor; import com.google.collide.shared.document.util.PositionUtils; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar.Remover; /*- * TODO: * - store enough info so we can safely skip the render step if * this was off-screen */ /** * A class to track changes in the document or editor state that result in a * render pass. */ class ChangeTracker implements Document.TextListener, ViewportModel.Listener, SelectionModel.SelectionListener, Buffer.SpacerListener, FocusManager.FocusListener { enum ChangeType { /** The viewport's top or bottom are now pointing to different lines */ VIEWPORT_SHIFT, /** The viewport had a line added or removed */ VIEWPORT_CONTENT, /** The contents of a line has changed */ DIRTY_LINE, /** The selection has changed */ SELECTION, /** The viewport's top or bottom line numbers have changed */ VIEWPORT_LINE_NUMBER } private class RenderCommand extends ScheduledCommandExecutor { @Override protected void execute() { /* * TODO: think about whether a render pass can cause a * change, if so, need to fix some stuff here like clearing/cloning the * changes BEFORE calling out to the renderer */ try { renderer.renderChanges(); } catch (Throwable t) { Log.error(getClass(), t); } clearChangeState(); } } /* * TODO: More cleanly group the variables that track changed * state */ /** Tracks the types of changes that occurred */ private final EnumSet<ChangeType> changes; /** * Tracks whether there was a content change that requires updating the top of * existing following lines */ private boolean hadContentChangeThatRepositionsFollowingLines; /** List of lines that need to be re-rendered */ private final JsonArray<Line> dirtyLines; private final LineUtils.LineVisitor dirtyMarkingLineVisitor = new LineVisitor() { @Override public boolean accept(Line line, int lineNumber, int beginColumn, int endColumn) { requestRenderLine(line); return true; } }; private final Buffer buffer; private final JsonArray<Remover> listenerRemovers; /** Command that is scheduled-finally from any callback */ private final RenderCommand renderCommand = new RenderCommand(); private final Renderer renderer; private final SelectionModel selection; private final ViewportModel viewport; /** * List of lines that were removed. These were in the viewport at time of * removal (and hence were most likely rendered) */ private final JsonArray<Line> viewportRemovedLines; /** * The line number of the topmost line that was added or removed, or * {@value Integer#MAX_VALUE} if there weren't any of these changes */ private int topmostContentChangedLineNumber; private final EnumSet<ViewportModel.Edge> viewportLineNumberChangedEdges = EnumSet .noneOf(ViewportModel.Edge.class); ChangeTracker(Renderer renderer, Buffer buffer, Document document, ViewportModel viewport, SelectionModel selection, FocusManager focusManager) { this.buffer = buffer; this.renderer = renderer; this.selection = selection; this.listenerRemovers = JsonCollections.createArray(); this.changes = EnumSet.noneOf(ChangeType.class); this.viewportRemovedLines = JsonCollections.createArray(); this.dirtyLines = JsonCollections.createArray(); this.viewport = viewport; attach(buffer, document, viewport, selection, focusManager); clearChangeState(); } public EnumSet<ChangeType> getChanges() { return changes; } public JsonArray<Line> getDirtyLines() { return dirtyLines; } public JsonArray<Line> getViewportRemovedLines() { return viewportRemovedLines; } public int getTopmostContentChangedLineNumber() { return topmostContentChangedLineNumber; } /** * Returns whether the {@link ChangeType#VIEWPORT_CONTENT} change type was one * that requires updating the position of the * {@link #getTopmostContentChangedLineNumber()} and all following * lines. */ public boolean hadContentChangeThatUpdatesFollowingLines() { return hadContentChangeThatRepositionsFollowingLines; } public EnumSet<ViewportModel.Edge> getViewportLineNumberChangedEdges() { return viewportLineNumberChangedEdges; } @Override public void onSelectionChange(Position[] oldSelectionRange, Position[] newSelectionRange) { /* * We only need to redraw those lines that either entered or left the * selection */ Position[] viewportRange = getViewportRange(); if (oldSelectionRange != null && newSelectionRange != null) { JsonArray<Position[]> differenceRanges = PositionUtils.getDifference(oldSelectionRange, newSelectionRange); for (int i = 0, n = differenceRanges.size(); i < n; i++) { markVisibleLinesDirty(differenceRanges.get(i), viewportRange); } } else if (oldSelectionRange != null) { markVisibleLinesDirty(oldSelectionRange, viewportRange); } else if (newSelectionRange != null) { markVisibleLinesDirty(newSelectionRange, viewportRange); } } private void markVisibleLinesDirty(Position[] dirtyRange, Position[] viewportRange) { /* * We can safely intersect with the viewport. The typical danger in doing * this right now is by the time things render, the viewport could have * shifted. But, in that case, the new viewport will have to be rendered * anyway, and thus the selection in that new viewport would be drawn * regardless of any dirty-marking we do here. */ Position[] visibleRange = PositionUtils.getIntersection(dirtyRange, viewportRange); if (visibleRange != null) { PositionUtils.visit(dirtyMarkingLineVisitor, visibleRange[0], visibleRange[1]); } } private Position[] getViewportRange() { return new Position[] {new Position(viewport.getTop(), 0), new Position(viewport.getBottom(), viewport.getBottomLine().getText().length() - 1)}; } @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { for (int i = 0, n = textChanges.size(); i < n; i++) { /* * For insertion, the second line through the second-to-last line can't * have existed in the document, so no point in marking them dirty. */ TextChange textChange = textChanges.get(i); Line line = textChange.getLine(); Line lastLine = textChange.getLastLine(); if (dirtyLines.indexOf(line) == -1) { dirtyLines.add(line); } if (line != lastLine && dirtyLines.indexOf(lastLine) == -1) { dirtyLines.add(lastLine); } } scheduleRender(ChangeType.DIRTY_LINE); } @Override public void onViewportContentChanged(ViewportModel viewport, int lineNumber, boolean added, JsonArray<Line> lines) { int relevantContentChangedLineNumber; if (!added && viewport.getTopLineNumber() == lineNumber - 1) { // TODO: rework this case is handled naturally /* * This handles the top viewport line being "removed" by backspacing on * column 0. In this case, no one else draws the new top line of the * viewport (the one that got the previous top line's contents appended to * it). */ relevantContentChangedLineNumber = viewport.getTopLineNumber(); } else { relevantContentChangedLineNumber = lineNumber; } if (!added) { for (int i = 0, n = lines.size(); i < n; i++) { Line curLine = lines.get(i); if (ViewportRenderer.isRendered(curLine)) { viewportRemovedLines.add(curLine); } } } /* * If there is a spacer in the viewport below the line number change, line numbers shift * non-uniformly around it. */ /* * TODO: actually implement the check for spacers in the viewport, not just * the document. */ handleContentChange(relevantContentChangedLineNumber, buffer.hasSpacers()); } @Override public void onViewportLineNumberChanged(ViewportModel viewport, Edge edge) { viewportLineNumberChangedEdges.add(edge); scheduleRender(ChangeType.VIEWPORT_LINE_NUMBER); } @Override public void onViewportShifted(ViewportModel viewport, LineInfo top, LineInfo bottom, LineInfo oldTop, LineInfo oldBottom) { scheduleRender(ChangeType.VIEWPORT_SHIFT); } @Override public void onFocusChange(boolean hasFocus) { /* * Schedule re-rendering of the lines in the selection so that we can update * the selection color based on focused state. Note that by the time we are * rendering, the selection could have changed. This is OK since in that * case, the new selection has to be rendered anyway, and it will render in * the correct color. */ if (selection.hasSelection()) { markVisibleLinesDirty(selection.getSelectionRange(true), getViewportRange()); } } public void requestRenderLine(Line line) { if (dirtyLines.indexOf(line) == -1) { dirtyLines.add(line); } scheduleRender(ChangeType.DIRTY_LINE); } void teardown() { for (int i = 0, n = listenerRemovers.size(); i < n; i++) { listenerRemovers.get(i).remove(); } renderCommand.cancel(); } private void attach(Buffer buffer, Document document, ViewportModel viewport, SelectionModel selection, FocusManager focusManager) { listenerRemovers.add(focusManager.getFocusListenerRegistrar().add(this)); listenerRemovers.add(document.getTextListenerRegistrar().add(this)); listenerRemovers.add(viewport.getListenerRegistrar().add(this)); listenerRemovers.add(selection.getSelectionListenerRegistrar().add(this)); listenerRemovers.add(buffer.getSpacerListenerRegistrar().add(this)); } private void clearChangeState() { changes.clear(); viewportRemovedLines.clear(); dirtyLines.clear(); topmostContentChangedLineNumber = Integer.MAX_VALUE; hadContentChangeThatRepositionsFollowingLines = false; viewportLineNumberChangedEdges.clear(); } @Override public void onSpacerAdded(Spacer spacer) { handleContentChange(spacer.getLineNumber(), true); } @Override public void onSpacerRemoved(Spacer spacer, Line oldLine, int oldLineNumber) { handleContentChange(oldLineNumber, true); } @Override public void onSpacerHeightChanged(Spacer spacer, int oldHeight) { handleContentChange(spacer.getLineNumber(), true); } private void handleContentChange(int lineNumber, boolean requiresRepositioningFollowingLines) { hadContentChangeThatRepositionsFollowingLines |= requiresRepositioningFollowingLines; if (topmostContentChangedLineNumber > lineNumber) { topmostContentChangedLineNumber = lineNumber; } scheduleRender(ChangeType.VIEWPORT_CONTENT); } private void scheduleRender(ChangeType change) { changes.add(change); renderCommand.scheduleFinally(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/renderer/ViewportRenderer.java
client/src/main/java/com/google/collide/client/editor/renderer/ViewportRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.renderer; import java.util.EnumSet; import collide.client.util.Elements; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.ViewportModel.Edge; import com.google.collide.client.editor.renderer.Renderer.LineLifecycleListener; import com.google.collide.client.testing.DebugAttributeSetter; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.Anchor.RemovalStrategy; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.gwt.user.client.Timer; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; /* * TODO: I need to do another pass at the rendering paths after * having written the first round. There some edge cases that I handle, but not * in the cleanest way (these are mostly around joining lines at the top and * bottom of the viewport.) */ // Note: All Lines in viewport's range will have a cached line number /** */ public class ViewportRenderer { /** * The animation controller deals with edge cases caused by multiple * animations being queued up, usually from the user holding down the enter or * backspace key so lines have their top rapidly changed. * */ private class AnimationController { private final Editor.View editorView; private boolean isAnimating = false; private boolean isDisabled = false; private final Timer animationFinishedTimer = new Timer() { @Override public void run() { isAnimating = false; if (isDisabled) { // Re-enable animation AnimationController.this.editorView.setAnimationEnabled(true); isDisabled = false; } } }; AnimationController(Editor.View editorView) { this.editorView = editorView; } /** * This is called right before a group of DOM changes that would cause an * animation (ex: setting element top). If elements on the page are already * in the middle of an animation, disable animations for a short period, * then re-enable them. Keep rescheduling the re-enable timer on additional * calls. */ void onBeforeAnimationStarted() { if (isAnimating) { if (!isDisabled) { editorView.setAnimationEnabled(false); isDisabled = true; } animationFinishedTimer.cancel(); } else { isAnimating = true; } animationFinishedTimer.schedule(Editor.ANIMATION_DURATION); } } /** Key for a {@link Line#getTag} that stores the rendered DOM element */ public static final String LINE_TAG_LINE_ELEMENT = "ViewportRenderer.element"; /** * Key for a {@link Line#getTag} that stores a reference to the anchor that is * used to cache the line number for this line (since we cache line numbers * for lines in the viewport) */ private static final String LINE_TAG_LINE_NUMBER_CACHE_ANCHOR = "ViewportRenderer.lineNumberCacheAnchor"; private static final AnchorType OLD_VIEWPORT_ANCHOR_TYPE = AnchorType.create( ViewportRenderer.class, "Old viewport"); private static final AnchorType VIEWPORT_RENDERER_ANCHOR_TYPE = AnchorType.create( ViewportRenderer.class, "viewport renderer"); public static boolean isRendered(Line line) { return getLineElement(line) != null; } private static Element getLineElement(Line line) { return line.getTag(LINE_TAG_LINE_ELEMENT); } /** * Control queued animations by disabling future animations temporarily if * another animation happens in here. */ private final AnimationController animationController; private final Buffer buffer; private final Document document; private final ListenerManager<LineLifecycleListener> lineLifecycleListenerManager; private final LineRendererController lineRendererController; private final ViewportModel viewport; /** * The bottom of the viewport when last rendered, or null if the viewport * hasn't been rendered yet */ private Anchor viewportOldBottomAnchor; /** * The top of the viewport when last rendered, or null if the viewport hasn't * been rendered yet */ private Anchor viewportOldTopAnchor; ViewportRenderer(Document document, Buffer buffer, ViewportModel viewport, Editor.View editorView, ListenerManager<LineLifecycleListener> lineLifecycleListenerManager) { this.document = document; this.buffer = buffer; this.lineLifecycleListenerManager = lineLifecycleListenerManager; this.lineRendererController = new LineRendererController(buffer); this.viewport = viewport; this.animationController = new AnimationController(editorView); } private void placeOldViewportAnchors() { AnchorManager anchorManager = document.getAnchorManager(); if (viewportOldTopAnchor == null) { viewportOldTopAnchor = anchorManager.createAnchor(OLD_VIEWPORT_ANCHOR_TYPE, viewport.getTopLine(), viewport.getTopLineNumber(), AnchorManager.IGNORE_COLUMN); viewportOldTopAnchor.setRemovalStrategy(RemovalStrategy.SHIFT); viewportOldBottomAnchor = anchorManager.createAnchor(OLD_VIEWPORT_ANCHOR_TYPE, viewport.getBottomLine(), viewport.getBottomLineNumber(), AnchorManager.IGNORE_COLUMN); viewportOldBottomAnchor.setRemovalStrategy(RemovalStrategy.SHIFT); } else { anchorManager.moveAnchor(viewportOldTopAnchor, viewport.getTopLine(), viewport.getTopLineNumber(), AnchorManager.IGNORE_COLUMN); anchorManager.moveAnchor(viewportOldBottomAnchor, viewport.getBottomLine(), viewport.getBottomLineNumber(), AnchorManager.IGNORE_COLUMN); } } void addLineRenderer(LineRenderer lineRenderer) { lineRendererController.addLineRenderer(lineRenderer); } void removeLineRenderer(LineRenderer lineRenderer) { lineRendererController.removeLineRenderer(lineRenderer); } void render() { renderViewportShift(true); } /** * Re-renders the lines marked as dirty. If the line was not previously * rendered, it will not be rendered here. */ void renderDirtyLines(JsonArray<Line> dirtyLines) { int maxLineLength = buffer.getMaxLineLength(); int newMaxLineLength = maxLineLength; for (int i = 0, n = dirtyLines.size(); i < n; i++) { Line line = dirtyLines.get(i); Element lineElement = getLineElement(line); if (lineElement == null) { /* * The line may have been in the viewport when marked as dirty, but it * is not anymore */ continue; } if (buffer.hasLineElement(lineElement)) { lineRendererController.renderLine(line, LineUtils.getCachedLineNumber(line), lineElement, false); } int lineLength = line.getText().length(); if (lineLength > newMaxLineLength) { newMaxLineLength = lineLength; } } if (newMaxLineLength != maxLineLength) { // TODO: need to shrink back down if the max line shrinks buffer.setMaxLineLength(newMaxLineLength); } } /** * Renders changes to the content of the viewport at a line level, for example * line removals or additions. * * @param removedLines these lines were in the viewport at time of removal */ void renderViewportContentChange(int beginLineNumber, JsonArray<Line> removedLines) { // Garbage collect the elements of removed lines for (int i = 0, n = removedLines.size(); i < n; i++) { Line line = removedLines.get(i); garbageCollectLine(line); } /* * New lines being rendered were at +createOffset below the viewport before * this render pass. */ /* * TODO: This won't be correct if deletion DocOps from the * frontend are also applied in the same rendering pass as a deletion. */ int createOffset = removedLines.size() * buffer.getEditorLineHeight(); if (beginLineNumber <= viewport.getBottomLineNumber()) { // Only fill or update lines if the content change affects the viewport LineInfo beginLine = viewport.getDocument().getLineFinder().findLine(viewport.getBottom(), beginLineNumber); animationController.onBeforeAnimationStarted(); fillOrUpdateLines(beginLine.line(), beginLine.number(), viewport.getBottomLine(), viewport.getBottomLineNumber(), createOffset); } } void renderViewportLineNumbersChanged(EnumSet<Edge> changedEdges) { if (changedEdges.contains(ViewportModel.Edge.TOP)) { /* * Collaborator added/removed lines above us, update the viewport lines * since their tops may have changed */ LineInfo top = viewport.getTop(); LineInfo bottom = viewport.getBottom(); fillOrUpdateLines(top.line(), top.number(), bottom.line(), bottom.number(), 0); } } /** * Renders changes to the viewport positioning. */ void renderViewportShift(boolean forceRerender) { LineInfo oldTop = viewportOldTopAnchor != null ? viewportOldTopAnchor.getLineInfo() : null; LineInfo oldBottom = viewportOldBottomAnchor != null ? viewportOldBottomAnchor.getLineInfo() : null; LineInfo top = viewport.getTop(); LineInfo bottom = viewport.getBottom(); if (oldTop == null || oldBottom == null || bottom.number() < oldTop.number() || top.number() > oldBottom.number() || forceRerender) { /* * The viewport does not overlap with its old position, GC old lines and * render all of the new ones (or we are forced to rerender everything) */ if (oldTop != null && oldBottom != null) { garbageCollectLines(oldTop.line(), oldTop.number(), oldBottom.line(), oldBottom.number()); } fillOrUpdateLines(top.line(), top.number(), bottom.line(), bottom.number(), 0); } else { // There is some overlap, so be more efficient with our update if (oldTop.number() < top.number()) { // The viewport moved down, need to GC the offscreen lines garbageCollectLines(top.line().getPreviousLine(), top.number() - 1, oldTop.line(), oldTop.number()); } else if (oldTop.number() > top.number()) { // The viewport moved up, need to fill with lines fillOrUpdateLines(top.line(), top.number(), oldTop.line().getPreviousLine(), oldTop.number() - 1, 0); } if (oldBottom.number() < bottom.number()) { // The viewport moved down, need to fill with lines fillOrUpdateLines(oldBottom.line().getNextLine(), oldBottom.number() + 1, bottom.line(), bottom.number(), 0); } else if (oldBottom.number() > bottom.number()) { // The viewport moved up, need to GC the offscreen lines garbageCollectLines(bottom.line().getNextLine(), bottom.number() + 1, oldBottom.line(), oldBottom.number()); } } } /** * Once torn down, this instance cannot be used again. */ void teardown() { } /** * Fills the buffer in the given range (inclusive). * * @param beginLineNumber the line number to start filling from * @param endLineNumber the line number of last line (inclusive) to finish * filling * @param createOffset the offset in pixels that this line would be at before * this rendering pass, used to animate in from offscreen */ public void fillOrUpdateLines(Line beginLine, int beginLineNumber, Line endLine, int endLineNumber, int createOffset) { Line curLine = beginLine; int curLineNumber = beginLineNumber; if (curLineNumber <= endLineNumber) { for (; curLineNumber <= endLineNumber && curLine != null; curLineNumber++) { createOrUpdateLineElement(curLine, curLineNumber, createOffset); curLine = curLine.getNextLine(); } } else { for (; curLineNumber >= endLineNumber && curLine != null; curLineNumber--) { createOrUpdateLineElement(curLine, curLineNumber, createOffset); curLine = curLine.getPreviousLine(); } } } private void garbageCollectLine(final Line line) { lineLifecycleListenerManager.dispatch(new Dispatcher<Renderer.LineLifecycleListener>() { @Override public void dispatch(LineLifecycleListener listener) { listener.onRenderedLineGarbageCollected(line); } }); Element element = line.getTag(LINE_TAG_LINE_ELEMENT); if (element != null && buffer.hasLineElement(element)) { element.removeFromParent(); line.putTag(LINE_TAG_LINE_ELEMENT, null); } handleLineLeftViewport(line); } /* * TODO: consider taking LineInfo and a offset for each of begin * and end. Callers right now do the offset manually, but that might lead to * them giving us a null Line or out-of-bounds line number */ public void garbageCollectLines(Line beginLine, int beginNumber, Line endLine, int endNumber) { if (beginNumber > endNumber) { // Swap so beginNumber < endNumber Line tmpLine = beginLine; int tmpNumber = beginNumber; beginLine = endLine; beginNumber = endNumber; endLine = tmpLine; endNumber = tmpNumber; } Line curLine = beginLine; for (int curNumber = beginNumber; curNumber <= endNumber && curLine != null; curNumber++) { garbageCollectLine(curLine); curLine = curLine.getNextLine(); } } private Element createOrUpdateLineElement(final Line line, final int lineNumber, int createOffset) { int top = buffer.calculateLineTop(lineNumber); Element element = getLineElement(line); boolean isCreatingElement = element == null; if (isCreatingElement) { element = Elements.createDivElement(); element.getStyle().setPosition(CSSStyleDeclaration.Position.ABSOLUTE); lineRendererController.renderLine(line, lineNumber, element, true); line.putTag(LINE_TAG_LINE_ELEMENT, element); } new DebugAttributeSetter().add("lineNum", Integer.toString(lineNumber)).on(element); if (!buffer.hasLineElement(element)) { element.getStyle().setTop(top + createOffset, CSSStyleDeclaration.Unit.PX); buffer.addLineElement(element); if (createOffset != 0) { /* * TODO: When enabling editor animations, reinvestigate * need for below */ // Force a browser layout so CSS3 animations transition properly. //element.getClientWidth(); element.getStyle().setTop(top, CSSStyleDeclaration.Unit.PX); } handleLineEnteredViewport(line, lineNumber, element); } else { element.getStyle().setTop(top, CSSStyleDeclaration.Unit.PX); } if (isCreatingElement) { lineLifecycleListenerManager.dispatch(new Dispatcher<Renderer.LineLifecycleListener>() { @Override public void dispatch(LineLifecycleListener listener) { listener.onRenderedLineCreated(line, lineNumber); } }); } else { lineLifecycleListenerManager.dispatch(new Dispatcher<Renderer.LineLifecycleListener>() { @Override public void dispatch(LineLifecycleListener listener) { listener.onRenderedLineShifted(line, lineNumber); } }); } return element; } private void handleLineEnteredViewport(Line line, int lineNumber, Element lineElement) { assert line.getTag(LINE_TAG_LINE_NUMBER_CACHE_ANCHOR) == null; Anchor anchor = line.getDocument() .getAnchorManager() .createAnchor(VIEWPORT_RENDERER_ANCHOR_TYPE, line, lineNumber, AnchorManager.IGNORE_COLUMN); // Stash this anchor as a line tag so we can remove it easily line.putTag(LINE_TAG_LINE_NUMBER_CACHE_ANCHOR, anchor); int lineLength = line.getText().length(); if (lineLength > buffer.getMaxLineLength()) { buffer.setMaxLineLength(lineLength); } } private void handleLineLeftViewport(Line line) { Anchor anchor = line.getTag(LINE_TAG_LINE_NUMBER_CACHE_ANCHOR); if (anchor == null) { /* * The line was in the viewport when the change occurred, but never * rendered with it there, so it never got a line number cache anchor * assigned */ return; } line.getDocument().getAnchorManager().removeAnchor(anchor); line.putTag(LINE_TAG_LINE_NUMBER_CACHE_ANCHOR, null); } void handleRenderCompleted() { placeOldViewportAnchors(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/RootActionExecutor.java
client/src/main/java/com/google/collide/client/editor/input/RootActionExecutor.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * Implementation of proxy that delegated execution to a list of executors. * */ public class RootActionExecutor implements ActionExecutor { /** * Object used to unregister delegate. */ public class Remover { public Remover(ActionExecutor instance) { this.instance = instance; } private ActionExecutor instance; public void remove() { delegates.remove(instance); } } private final JsonArray<ActionExecutor> delegates = JsonCollections.createArray(); public Remover addDelegate(ActionExecutor delegate) { delegates.add(delegate); return new Remover(delegate); } @Override public boolean execute(String actionName, InputScheme scheme, SignalEvent event) { for (int i = 0, l = delegates.size(); i < l; i++) { if (delegates.get(i).execute(actionName, scheme, event)) { return true; } } return false; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/VimScheme.java
client/src/main/java/com/google/collide/client/editor/input/VimScheme.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.JsoIntMap; import org.waveprotocol.wave.client.common.util.SignalEvent; import org.waveprotocol.wave.client.common.util.SignalEvent.MoveUnit; import collide.client.util.Elements; import com.google.collide.client.editor.search.SearchModel; import com.google.collide.client.editor.selection.LocalCursorController; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.editor.selection.SelectionModel.MoveAction; import com.google.collide.client.util.input.CharCodeWithModifiers; import com.google.collide.client.util.input.KeyCodeMap; import com.google.collide.client.util.input.ModifierKeys; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.document.util.PositionUtils; import com.google.collide.shared.util.ScopeMatcher; import com.google.collide.shared.util.StringUtils; import com.google.collide.shared.util.TextUtils; import com.google.common.base.Preconditions; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; /** * Basic Vi(m) keybinding support. This is limited to single file operations. * This includes the main Vim modes for Command, Visual, Insert, and single-line * search/command entry. */ public class VimScheme extends InputScheme { private static final JsoIntMap<MoveAction> CHAR_MOVEMENT_KEYS_MAPPING = JsoIntMap.create(); private static final JsoIntMap<MoveAction> LINE_MOVEMENT_KEYS_MAPPING = JsoIntMap.create(); /** * Command mode mirrors Vim's command mode for performing commands from single * keypresses. */ InputMode commandMode; /** * Insert mode can only insert text or escape back to command mode. */ InputMode insertMode; /** * Command capture mode gets switched to from command mode when a ":" is typed * until the enter key is pressed, and the resulting text between : and * <enter> is used as the argument to {@link #doColonCommand(StringBuilder)}. */ InputMode commandCaptureMode; /** * Search capture mode gets switched to from command mode when a "/" is typed * and will highlight whatever text is typed in the current document until * escape or enter are pressed. */ InputMode searchCaptureMode; Element statusHeader; boolean inVisualMode; MoveUnit visualMoveUnit; /** Any numbers typed before a command shortcut. */ private StringBuilder numericPrefixText = new StringBuilder(); private StringBuilder command; private StringBuilder searchTerm; private String clipboard; private boolean isLineCopy; private static enum Modes { COMMAND, INSERT, COMMAND_CAPTURE, SEARCH_CAPTURE } // The order of characters here needs to match private static final String OPENING_GROUPS = "{[("; private static final String CLOSING_GROUPS = "}])"; static { CHAR_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'h'), MoveAction.LEFT); CHAR_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'j'), MoveAction.DOWN); CHAR_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'k'), MoveAction.UP); CHAR_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'l'), MoveAction.RIGHT); LINE_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'h'), MoveAction.LINE_START); LINE_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'j'), MoveAction.DOWN); LINE_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'k'), MoveAction.UP); LINE_MOVEMENT_KEYS_MAPPING.put( CharCodeWithModifiers.computeKeyDigest(ModifierKeys.NONE, 'l'), MoveAction.LINE_END); } /** * TODO: Refactor shortcut system to separate activation key * definition (the "Shortcut") from the actual shortcut function (the * "Action") as some shortcuts have duplicate actions. */ public VimScheme(InputController inputController) { super(inputController); commandMode = new InputMode() { @Override public void setup() { setStatus("-- COMMAND --"); inVisualMode = false; numericPrefixText.setLength(0); LocalCursorController cursor = getInputController().getEditor().getCursorController(); cursor.setBlockMode(true); cursor.setColor("blue"); getInputController().getEditor().getSelection().deselect(); } @Override public void teardown() { getInputController().getEditor().getCursorController().resetCursorView(); } @Override public boolean onDefaultInput(SignalEvent signal, char character) { // navigate here int letter = KeyCodeMap.getKeyFromEvent(signal); int modifiers = ModifierKeys.computeModifiers(signal); modifiers = modifiers & ~ModifierKeys.SHIFT; int strippedKeyDigest = CharCodeWithModifiers.computeKeyDigest(modifiers, letter); JsoIntMap<MoveAction> movementKeysMapping = getMovementKeysMapping(); if (movementKeysMapping.containsKey(strippedKeyDigest)) { MoveAction action = movementKeysMapping.get(strippedKeyDigest); getScheme().getInputController().getSelection().move(action, inVisualMode); return true; } if (tryAddNumericPrefix((char) letter)) { return true; } numericPrefixText.setLength(0); return false; } /** * Paste events. These can come in from native Command+V or forced via * holding a local clipboard/buffer of any text copied within the editor. */ @Override public boolean onDefaultPaste(SignalEvent signal, String text) { handlePaste(text, true); return true; } }; addMode(Modes.COMMAND, commandMode); /* * Command+Alt+V - Switch from Vim to Default Scheme */ commandMode.addShortcut(new EventShortcut(ModifierKeys.ACTION | ModifierKeys.ALT, 'v') { @Override public boolean event(InputScheme scheme, SignalEvent event) { getInputController().setActiveInputScheme(getInputController().nativeScheme); return true; } }); /* * ESC, ACTION+[ - reset state in command mode */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.ESC) { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.COMMAND); return true; } }); commandMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, '[') { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.COMMAND); return true; } }); /* * TODO: extract common visual mode switching code. */ /* * v - Switch to visual mode (character) */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'v') { @Override public boolean event(InputScheme scheme, SignalEvent event) { setStatus("-- VISUAL (char) --"); inVisualMode = true; visualMoveUnit = MoveUnit.CHARACTER; // select the character the cursor is over now SelectionModel selectionModel = getInputController().getEditor().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); int cursorColumn = selectionModel.getCursorColumn(); selectionModel.setSelection(cursorLineInfo, cursorColumn, cursorLineInfo, cursorColumn + 1); return true; } }); /* * V - Switch to visual mode (line) */ /* * TODO: Doesn't exactly match vim's visual-line mode, force * selections of entire lines. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'V') { @Override public boolean event(InputScheme scheme, SignalEvent event) { setStatus("-- VISUAL (line) --"); inVisualMode = true; visualMoveUnit = MoveUnit.LINE; // move cursor to beginning of current line, select to column 0 of next // line SelectionModel selectionModel = getInputController().getEditor().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); LineInfo nextLineInfo = new LineInfo(cursorLineInfo.line().getNextLine(), cursorLineInfo.number() + 1); selectionModel.setSelection(cursorLineInfo, 0, nextLineInfo, 0); return true; } }); /* * i - Switch to insert mode */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'i') { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.INSERT); return true; } }); /* * A - Jump to end of line, enter insert mode. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'A') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); int lastColumn = LineUtils.getLastCursorColumn(cursorLineInfo.line()); selectionModel.setCursorPosition(cursorLineInfo, lastColumn); switchMode(Modes.INSERT); return true; } }); /* * O - Insert line above, enter insert mode. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'O') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); Document document = getInputController().getEditor().getDocument(); Line cursorLine = selectionModel.getCursorLine(); int cursorLineNumber = selectionModel.getCursorLineNumber(); document.insertText(cursorLine, 0, "\n"); selectionModel.setCursorPosition(new LineInfo(cursorLine, cursorLineNumber), 0); switchMode(Modes.INSERT); return true; } }); /* * o - Insert line below, enter insert mode. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'o') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); Document document = getInputController().getEditor().getDocument(); Line cursorLine = selectionModel.getCursorLine(); int cursorLineNumber = selectionModel.getCursorLineNumber(); document.insertText(cursorLine, LineUtils.getLastCursorColumn(cursorLine), "\n"); selectionModel.setCursorPosition(new LineInfo(cursorLine.getNextLine(), cursorLineNumber + 1), 0); switchMode(Modes.INSERT); return true; } }); /* * : - Switch to colon capture mode for commands. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, ':') { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.COMMAND_CAPTURE); return true; } }); /* * "/" - Switch to search mode. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '/') { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.SEARCH_CAPTURE); return true; } }); commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '*') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); String word = TextUtils.getWordAtColumn(selectionModel.getCursorLine().getText(), selectionModel.getCursorColumn()); if (word == null) { return true; } switchMode(Modes.SEARCH_CAPTURE); searchTerm.append(word); doPartialSearch(); drawSearchTerm(); return true; } }); /* * Movement */ /* * ^,0 - Move to first character in line. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '^') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); selectionModel.setCursorPosition(cursorLineInfo, 0); return true; } }); commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '0') { @Override public boolean event(InputScheme scheme, SignalEvent event) { if (tryAddNumericPrefix('0')) { return true; } SelectionModel selectionModel = getInputController().getEditor().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); selectionModel.setCursorPosition(cursorLineInfo, 0); return true; } }); /* * $ - Move to end of line. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '$') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); Line cursorLine = selectionModel.getCursorLine(); LineInfo cursorLineInfo = new LineInfo(cursorLine, selectionModel.getCursorLineNumber()); selectionModel.setCursorPosition(cursorLineInfo, LineUtils.getLastCursorColumn(cursorLine)); return true; } }); /* * w - move the cursor to the first character of the next word. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'w') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); String text = selectionModel.getCursorLine().getText(); int column = selectionModel.getCursorColumn(); column = TextUtils.moveByWord(text, column, true, false); if (column == -1) { Line cursorLine = cursorLineInfo.line().getNextLine(); if (cursorLine != null) { cursorLineInfo = new LineInfo(cursorLine, cursorLineInfo.number() + 1); column = 0; } else { column = LineUtils.getLastCursorColumn(cursorLine); // at last character // in document } } selectionModel.setCursorPosition(cursorLineInfo, column); return true; } }); /* * b - move the cursor to the first character of the previous word. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'b') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); String text = selectionModel.getCursorLine().getText(); int column = selectionModel.getCursorColumn(); column = TextUtils.moveByWord(text, column, false, false); if (column == -1) { Line cursorLine = cursorLineInfo.line().getPreviousLine(); if (cursorLine != null) { cursorLineInfo = new LineInfo(cursorLine, cursorLineInfo.number() - 1); column = LineUtils.getLastCursorColumn(cursorLine); } else { column = 0; // at first character in document } } selectionModel.setCursorPosition(cursorLineInfo, column); return true; } }); /* * e - move the cursor to the last character of the next word. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'e') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); String text = selectionModel.getCursorLine().getText(); int column = selectionModel.getCursorColumn(); column = TextUtils.moveByWord(text, column, true, true); if (column == -1) { Line cursorLine = cursorLineInfo.line().getNextLine(); if (cursorLine != null) { cursorLineInfo = new LineInfo(cursorLine, cursorLineInfo.number() + 1); column = 0; } else { // at the last character in the document column = LineUtils.getLastCursorColumn(cursorLine); } } selectionModel.setCursorPosition(cursorLineInfo, column); return true; } }); /* * % - jump to the next matching {}, [] or () character if the cursor is * over one of the two. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '%') { @Override public boolean event(InputScheme scheme, SignalEvent event) { final SelectionModel selectionModel = getInputController().getSelection(); Document document = getInputController().getEditor().getDocument(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); String text = selectionModel.getCursorLine().getText(); final char cursorChar = text.charAt(selectionModel.getCursorColumn()); final char searchChar; final boolean searchingForward = OPENING_GROUPS.indexOf(cursorChar) >= 0; final Position searchingTo; if (searchingForward) { searchChar = CLOSING_GROUPS.charAt(OPENING_GROUPS.indexOf(cursorChar)); searchingTo = new Position(new LineInfo(document.getLastLine(), document.getLastLineNumber()), document.getLastLine().length()); } else if (CLOSING_GROUPS.indexOf(cursorChar) >= 0) { searchChar = OPENING_GROUPS.charAt(CLOSING_GROUPS.indexOf(cursorChar)); searchingTo = new Position(new LineInfo(document.getFirstLine(), 0), 0); } else { return true; // not on a valid starting character } Position startingPosition = new Position(cursorLineInfo, selectionModel.getCursorColumn() + (searchingForward ? 0 : 1)); PositionUtils.visit(new LineUtils.LineVisitor() { // keep a stack to match the correct corresponding bracket ScopeMatcher scopeMatcher = new ScopeMatcher(searchingForward, cursorChar, searchChar); @Override public boolean accept(Line line, int lineNumber, int beginColumn, int endColumn) { int column; String text = line.getText().substring(beginColumn, endColumn); column = scopeMatcher.searchNextLine(text); if (column >= 0) { selectionModel .setCursorPosition(new LineInfo(line, lineNumber), column + beginColumn); return false; } return true; } }, startingPosition, searchingTo); return true; } }); /* * } - next paragraph. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '}') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); int lineNumber = cursorLineInfo.number(); boolean skippingEmptyLines = true; Line line; for (line = cursorLineInfo.line(); line.getNextLine() != null; line = line.getNextLine(), lineNumber++) { String text = line.getText(); text = text.substring(0, text.length() - (text.endsWith("\n") ? 1 : 0)); boolean isEmptyLine = text.trim().length() > 0; if (skippingEmptyLines) { // check if this line is empty if (isEmptyLine) { skippingEmptyLines = false; // non-empty line } } else { // check if this line is not empty if (!isEmptyLine) { break; } } } selectionModel.setCursorPosition(new LineInfo(line, lineNumber), 0); return true; } }); /* * TODO: merge both paragraph searching blocks together. */ /* * { - previous paragraph. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, '{') { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getSelection(); LineInfo cursorLineInfo = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); int lineNumber = cursorLineInfo.number(); boolean skippingEmptyLines = true; Line line; for (line = cursorLineInfo.line(); line.getPreviousLine() != null; line = line.getPreviousLine(), lineNumber--) { String text = line.getText(); text = text.substring(0, text.length() - (text.endsWith("\n") ? 1 : 0)); if (skippingEmptyLines) { // check if this line is empty if (text.trim().length() > 0) { skippingEmptyLines = false; // non-empty line } } else { // check if this line is not empty if (text.trim().length() > 0) { // not empty, continue } else { break; } } } selectionModel.setCursorPosition(new LineInfo(line, lineNumber), 0); return true; } }); /* * Cmd+u - page up. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'u') { @Override public boolean event(InputScheme scheme, SignalEvent event) { getInputController().getSelection().move(MoveAction.PAGE_UP, inVisualMode); return true; } }); /* * Cmd+d - page down. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'd') { @Override public boolean event(InputScheme scheme, SignalEvent event) { getInputController().getSelection().move(MoveAction.PAGE_DOWN, inVisualMode); return true; } }); /* * Ngg - move cursor to line N, or first line by default. */ commandMode.addShortcut(new StreamShortcut("gg") { @Override public boolean event(InputScheme scheme, SignalEvent event) { moveCursorToLine(getPrefixValue(), true); return true; } }); /* * NG - move cursor to line N, or last line by default. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'G') { @Override public boolean event(InputScheme scheme, SignalEvent event) { moveCursorToLine(getPrefixValue(), false); return true; } }); /* * Text manipulation */ /* * x - Delete one character to right of cursor, or the current selection. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'x') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteCharacter(true); return true; } }); /* * X - Delete one character to left of cursor. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'X') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteCharacter(false); return true; } }); /* * p - Paste after cursor. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'p') { @Override public boolean event(InputScheme scheme, SignalEvent event) { if (clipboard != null && clipboard.length() > 0) { handlePaste(clipboard, true); } return true; } }); /* * P - Paste before cursor. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'P') { @Override public boolean event(InputScheme scheme, SignalEvent event) { if (clipboard != null && clipboard.length() > 0) { handlePaste(clipboard, false); } return true; } }); /* * Nyy - Copy N lines. If there is already a selection, copy that instead. */ commandMode.addShortcut(new StreamShortcut("yy") { @Override public boolean event(InputScheme scheme, SignalEvent event) { SelectionModel selectionModel = getInputController().getEditor().getSelection(); if (selectionModel.hasSelection()) { isLineCopy = (visualMoveUnit == MoveUnit.LINE); } else { int numLines = getPrefixValue(); if (numLines <= 0) { numLines = 1; } selectNextNLines(numLines); isLineCopy = false; } Preconditions.checkState(selectionModel.hasSelection()); getInputController().prepareForCopy(); Position[] selectionRange = selectionModel.getSelectionRange(true); clipboard = LineUtils.getText(selectionRange[0].getLine(), selectionRange[0].getColumn(), selectionRange[1].getLine(), selectionRange[1].getColumn()); selectionModel.deselect(); switchMode(Modes.COMMAND); return false; } }); /* * Ndd - Cut N lines. */ commandMode.addShortcut(new StreamShortcut("dd") { @Override public boolean event(InputScheme scheme, SignalEvent event) { int numLines = getPrefixValue(); if (numLines <= 0) { numLines = 1; } SelectionModel selectionModel = getInputController().getEditor().getSelection(); selectNextNLines(numLines); Preconditions.checkState(selectionModel.hasSelection()); getInputController().prepareForCopy(); Position[] selectionRange = selectionModel.getSelectionRange(true); clipboard = LineUtils.getText(selectionRange[0].getLine(), selectionRange[0].getColumn(), selectionRange[1].getLine(), selectionRange[1].getColumn()); selectionModel.deleteSelection(getInputController().getEditorDocumentMutator()); return false; } }); /* * >> - indent line. */ commandMode.addShortcut(new StreamShortcut(">>") { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().indentSelection(); return true; } }); /* * << - dedent line. */ commandMode.addShortcut(new StreamShortcut("<<") { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().dedentSelection(); return true; } }); /* * u - Undo. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'u') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().getEditor().undo(); return true; } }); /* * ACTION+r - Redo. */ commandMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'r') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().getEditor().redo(); return true; } }); /** * n - next search match */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'n') { @Override public boolean event(InputScheme scheme, SignalEvent event) { doSearch(true); return true; } }); /** * N - previous search match */ commandMode.addShortcut(new EventShortcut(ModifierKeys.NONE, 'N') { @Override public boolean event(InputScheme scheme, SignalEvent event) { doSearch(false); return true; } }); insertMode = new InputMode() { @Override public void setup() { setStatus("-- INSERT --"); } @Override public void teardown() { } @Override public boolean onDefaultInput(SignalEvent signal, char character) { int letter = KeyCodeMap.getKeyFromEvent(signal); int modifiers = ModifierKeys.computeModifiers(signal); modifiers = modifiers & ~ModifierKeys.SHIFT; int strippedKeyDigest = CharCodeWithModifiers.computeKeyDigest(modifiers, letter); JsoIntMap<MoveAction> movementKeysMapping = DefaultScheme.MOVEMENT_KEYS_MAPPING; if (movementKeysMapping.containsKey(strippedKeyDigest)) { MoveAction action = movementKeysMapping.get(strippedKeyDigest); getScheme().getInputController().getSelection().move(action, false); return true; } InputController input = getInputController(); SelectionModel selection = input.getSelection(); int column = selection.getCursorColumn(); if (!signal.getCommandKey() && KeyCodeMap.isPrintable(letter)) { String text = Character.toString((char) letter); // insert a single character input.getEditorDocumentMutator().insertText(selection.getCursorLine(), selection.getCursorLineNumber(), column, text); return true; } return false; // let it fall through } @Override public boolean onDefaultPaste(SignalEvent signal, String text) { return false; } }; addMode(Modes.INSERT, insertMode); /* * ESC, ACTION+[ - Switch to command mode. */ insertMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.ESC) { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.COMMAND); return true; } }); insertMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, '[') { @Override public boolean event(InputScheme scheme, SignalEvent event) { switchMode(Modes.COMMAND); return true; } }); /* * BACKSPACE - Native behavior. */ insertMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.BACKSPACE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { getInputController().deleteCharacter(false); return true; } }); /* * DELETE - Native behavior. */ insertMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.DELETE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { getInputController().deleteCharacter(true); return true; } }); /* * TAB - Insert a tab. */ insertMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.TAB) { @Override
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/com/google/collide/client/editor/input/ActionExecutor.java
client/src/main/java/com/google/collide/client/editor/input/ActionExecutor.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Interface used to resolve and execute action. */ public interface ActionExecutor { boolean execute(String actionName, InputScheme scheme, SignalEvent event); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/Shortcut.java
client/src/main/java/com/google/collide/client/editor/input/Shortcut.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Abstract Shortcut class. Override event function to implement a callback. */ public interface Shortcut { // TODO: separate the keybinding and action definitions public abstract boolean event(InputScheme scheme, SignalEvent event); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/InputController.java
client/src/main/java/com/google/collide/client/editor/input/InputController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; import collide.client.util.BrowserUtils; import collide.client.util.Elements; import com.google.collide.client.document.linedimensions.LineDimensionsUtils; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.Editor.KeyListener; import com.google.collide.client.editor.Editor.NativeKeyUpListener; import com.google.collide.client.editor.Editor.ReadOnlyListener; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.SignalEventUtils; import com.google.collide.client.util.logging.Log; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineFinder; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.TextUtils; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; import elemental.events.TextEvent; import elemental.html.TextAreaElement; /** * Controller for taking input from the user. This manages an offscreen textarea * that receives the user's entered text. * * The lifecycle of this class is tied to the editor that owns it. * */ public class InputController { // TODO: move to elemental private static final String EVENT_TEXTINPUT = "textInput"; final InputScheme nativeScheme; final InputScheme vimScheme; private Document document; private Editor editor; private DocumentMutator editorDocumentMutator; private final TextAreaElement inputElement; private InputScheme activeInputScheme = null; private final ListenerManager<KeyListener> keyListenerManager = ListenerManager.create(); private final ListenerManager<NativeKeyUpListener> nativeKeyUpListenerManager = ListenerManager .create(); private SelectionModel selection; private ViewportModel viewport; private final RootActionExecutor actionExecutor; public InputController() { inputElement = createInputElement(); actionExecutor = new RootActionExecutor(); nativeScheme = new DefaultScheme(this); vimScheme = new VimScheme(this); } public Document getDocument() { return document; } public Editor getEditor() { return editor; } public DocumentMutator getEditorDocumentMutator() { return editorDocumentMutator; } public Element getInputElement() { return inputElement; } public String getInputText() { return inputElement.getValue(); } public ListenerRegistrar<KeyListener> getKeyListenerRegistrar() { return keyListenerManager; } public ListenerRegistrar<NativeKeyUpListener> getNativeKeyUpListenerRegistrar() { return nativeKeyUpListenerManager; } public SelectionModel getSelection() { return selection; } public void handleDocumentChanged(Document document, SelectionModel selection, ViewportModel viewport) { this.document = document; this.selection = selection; this.viewport = viewport; } public void initializeFromEditor(Editor editor, DocumentMutator editorDocumentMutator) { this.editor = editor; this.editorDocumentMutator = editorDocumentMutator; editor.getReadOnlyListenerRegistrar().add(new ReadOnlyListener() { @Override public void onReadOnlyChanged(boolean isReadOnly) { handleReadOnlyChanged(isReadOnly); } }); handleReadOnlyChanged(editor.isReadOnly()); } private void handleReadOnlyChanged(boolean isReadOnly) { if (isReadOnly) { setActiveInputScheme(new ReadOnlyScheme(this)); } else { setActiveInputScheme(nativeScheme); } } public void setActiveInputScheme(InputScheme inputScheme) { if (this.activeInputScheme != null) { this.activeInputScheme.teardown(); } this.activeInputScheme = inputScheme; this.activeInputScheme.setup(); } public void setInputText(String text) { inputElement.setValue(text); } public void setSelection(SelectionModel selection) { this.selection = selection; } boolean dispatchKeyPress(final SignalEvent signalEvent) { class KeyDispatcher implements Dispatcher<KeyListener> { boolean handled; @Override public void dispatch(KeyListener listener) { handled |= listener.onKeyPress(signalEvent); } } KeyDispatcher keyDispatcher = new KeyDispatcher(); keyListenerManager.dispatch(keyDispatcher); return keyDispatcher.handled; } boolean dispatchKeyUp(final Event event) { class NativeKeyUpDispatcher implements Dispatcher<Editor.NativeKeyUpListener> { boolean handled; @Override public void dispatch(NativeKeyUpListener listener) { handled |= listener.onNativeKeyUp(event); } } NativeKeyUpDispatcher nativeKeyUpDispatcher = new NativeKeyUpDispatcher(); nativeKeyUpListenerManager.dispatch(nativeKeyUpDispatcher); return nativeKeyUpDispatcher.handled; } private TextAreaElement createInputElement() { final TextAreaElement inputElement = Elements.createTextAreaElement(); // Ensure it is offscreen inputElement.getStyle().setPosition(CSSStyleDeclaration.Position.ABSOLUTE); inputElement.getStyle().setLeft("-100000px"); inputElement.getStyle().setTop("0"); inputElement.getStyle().setHeight("1px"); inputElement.getStyle().setWidth("1px"); /* * Firefox doesn't seem to respect just the NOWRAP value, so we need to set * the legacy wrap attribute. */ inputElement.setAttribute("wrap", "off"); // Attach listeners /* * For text events, call inputHandler.handleInput(event, text) if the text * entered was > 1 character -> from a paste event. This gets fed directly * into the document. Single keypresses all get captured by signalEventListener * and passed through the shortcut system. * * TODO: This isn't actually true, there could be paste events * of only one character. Change this to check if the event was a clipboard * event. */ inputElement.addEventListener(EVENT_TEXTINPUT, new EventListener() { @Override public void handleEvent(Event event) { /* * TODO: figure out best event to listen to. Tried "input", * but see http://code.google.com/p/chromium/issues/detail?id=76516 */ String text = ((TextEvent) event).getData(); if (text.length() <= 1) { return; } setInputText(""); activeInputScheme.handleEvent(SignalEventUtils.create(event), text); } }, false); if (BrowserUtils.isFirefox()) { inputElement.addEventListener(Event.INPUT, new EventListener() { @Override public void handleEvent(Event event) { /* * TODO: FF doesn't support textInput, and Chrome's input * is buggy. */ String text = getInputText(); if (text.length() <= 1) { return; } setInputText(""); activeInputScheme.handleEvent(SignalEventUtils.create(event), text); event.preventDefault(); event.stopPropagation(); } }, false); } EventListener signalEventListener = new EventListener() { @Override public void handleEvent(Event event) { SignalEvent signalEvent = SignalEventUtils.create(event); if (signalEvent != null) { processSignalEvent(signalEvent); } else if ("keyup".equals(event.getType())) { boolean handled = dispatchKeyUp(event); if (handled) { // Prevent any browser handling. event.preventDefault(); event.stopPropagation(); } } } }; /* * Attach to all of key events, and the SignalEvent logic will filter * appropriately */ inputElement.addEventListener(Event.KEYDOWN, signalEventListener, false); inputElement.addEventListener(Event.KEYPRESS, signalEventListener, false); inputElement.addEventListener(Event.KEYUP, signalEventListener, false); inputElement.addEventListener(Event.COPY, signalEventListener, false); inputElement.addEventListener(Event.PASTE, signalEventListener, false); inputElement.addEventListener(Event.CUT, signalEventListener, false); return inputElement; } @VisibleForTesting public void processSignalEvent(SignalEvent signalEvent) { boolean handled = dispatchKeyPress(signalEvent); if (!handled) { if (signalEvent.isCopyEvent() || signalEvent.isCutEvent()) { prepareForCopy(); if (signalEvent.isCutEvent() && selection.hasSelection()) { selection.deleteSelection(editorDocumentMutator); } // These events are special cased, nothing else should happen. return; } /* * Send all keypresses through here. */ try { handled = activeInputScheme.handleEvent(signalEvent, ""); } catch (Throwable t) { Log.error(getClass(), t); } } if (handled) { // Prevent any browser handling. signalEvent.preventDefault(); signalEvent.stopPropagation(); setInputText(""); } } public void prepareForCopy() { if (!selection.hasSelection()) { // TODO: Discuss Ctrl-X feature. return; } Position[] selectionRange = selection.getSelectionRange(true); String selectionText = LineUtils.getText( selectionRange[0].getLine(), selectionRange[0].getColumn(), selectionRange[1].getLine(), selectionRange[1].getColumn()); setInputText(selectionText); inputElement.select(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { /* * The text has been copied by now, so clear it (if the text was large, * it would cause slow layout) */ setInputText(""); } }); } /** * Moves all selected lines down by deleting then inserting Lines */ public void moveLinesDown() { //expand selection to fill all affected lines Document doc = editor.getDocument(); LineFinder finder = doc.getLineFinder(); Line cursorLine = selection.getCursorLine(); //on no selection, select the line the cursor is on if (!selection.hasSelection()){ int selectionEnd = LineUtils.getLastCursorColumn(cursorLine); LineInfo selectStart = finder.findLine(cursorLine); if (selectionEnd==0){ //special case, the cursor is on a line without text. //insert a new line below cursor line, editor.getEditorDocumentMutator().insertText(selectStart.line().getNextLine().getNextLine(), 0, "\n"); //delete cursor line TextChange change = editor.getEditorDocumentMutator().deleteText( cursorLine, 0, 1); //readjust cursor selectStart = finder.findLine(change.getLastLineNumber()+1); selection.setCursorPosition(selectStart, 0); return; } //make sure selection fills cursor line selection.setSelection(selectStart, 0, selectStart, selectionEnd); } assert selection.hasSelection() : "No text selected, cannot complete move operation"; //grab the lines we need Position[] selectionRange = selection.getSelectionRange(true); LineInfo start = selectionRange[0].getLineInfo(); LineInfo end = selectionRange[1].getLineInfo(); //if the cursor ends on the first column, we need to advance our range one line if (selection.isCursorAtEndOfSelection()&&selection.getCursorColumn()==0){ end.moveToNext(); } int lastCol = LineUtils.getLastCursorColumn(end.line()); //copy the text we want to move String move = LineUtils.getText(start.line(), 0, end.line(), lastCol); //determine size of delete required int deleteCount = LineUtils.getTextCount(start.line(), 0, end.line(), LineUtils.getLastCursorColumn(end.line())); //delete previous editor.getEditorDocumentMutator().deleteText( start.line(), start.number(),0, deleteCount); //insert new copy TextChange change = editor.getEditorDocumentMutator().insertText( start.line().getNextLine(), start.number()+1,0, move,true ); //reselect the moved text end = finder.findLine(change.getLastLineNumber()+(end.number()-start.number())); selection.setSelection( new LineInfo(change.getLine(),change.getLineNumber()) , 0 ,end,lastCol ); } /** * Moves all selected lines up by deleting then inserting Lines */ public void moveLinesUp() { //expand selection to fill all affected lines Document doc = editor.getDocument(); LineFinder finder = doc.getLineFinder(); Line cursorLine = selection.getCursorLine(); //on no selection, select the line the cursor is on if (!selection.hasSelection()){ int selectionEnd = LineUtils.getLastCursorColumn(cursorLine); LineInfo selectStart = finder.findLine(cursorLine); if (selectionEnd==0){ //special case, the cursor is on a line without text. //insert a new line above cursor line, editor.getEditorDocumentMutator().insertText(selectStart.line().getPreviousLine(), 0, "\n"); //delete cursor line TextChange change = editor.getEditorDocumentMutator().deleteText( cursorLine, 0, 1); //readjust cursor selectStart = finder.findLine(change.getLineNumber()-2); selection.setCursorPosition(selectStart, 0); return; } //make sure selection fills cursor line selection.setSelection(selectStart, 0, selectStart, selectionEnd); } assert selection.hasSelection() : "No text selected, cannot complete move operation"; //grab the lines we need Position[] selectionRange = selection.getSelectionRange(true); LineInfo start = selectionRange[0].getLineInfo(); LineInfo end = selectionRange[1].getLineInfo(); //if the cursor ends on the first column, we need to advance our range one line if (selection.isCursorAtEndOfSelection()&&selection.getCursorColumn()==0){ end.moveToNext(); } //copy the text we want to move int lastCol = LineUtils.getLastCursorColumn(end.line()); String move = LineUtils.getText(start.line(), 0, end.line(), lastCol); //determine size of delete required int deleteCount = LineUtils.getTextCount(start.line(), 0, end.line(), LineUtils.getLastCursorColumn(end.line())); //delete previous editor.getEditorDocumentMutator().deleteText( start.line(), start.number(),0, deleteCount); //insert new copy TextChange change = editor.getEditorDocumentMutator().insertText( start.line().getPreviousLine(), start.number()-1,0, move,true ); //reselect the moved text end = finder.findLine(change.getLastLineNumber()+(end.number()-start.number())); selection.setSelection( new LineInfo(change.getLine(),change.getLineNumber()) , 0 ,end,lastCol ); } /** * Add a tab character to the beginning of each line in the current selection, * or at the current cursor position if no text is selected. */ // TODO: This should probably be a setting, tabs or spaces public void handleTab() { if (selection.hasMultilineSelection()) { indentSelection(); } else { getEditorDocumentMutator().insertText(selection.getCursorLine(), selection.getCursorLineNumber(), selection.getCursorColumn(), LineDimensionsUtils.getTabAsSpaces()); } } public void indentSelection() { selection.adjustSelectionIndentation( editorDocumentMutator, LineDimensionsUtils.getTabAsSpaces(), true); } /** * Removes the indentation from the beginning of each line of a multiline * selection. */ public void dedentSelection() { selection.adjustSelectionIndentation( editorDocumentMutator, LineDimensionsUtils.getTabAsSpaces(), false); } /** * Delete a character around the current cursor, and take care of joining lines * together if the delete removes a newline. This is used to implement backspace * and delete, depending upon the afterCursor argument. * * @param afterCursor if true, delete the character to the right of the cursor */ public void deleteCharacter(boolean afterCursor) { if (tryDeleteSelection()) { return; } Line cursorLine = selection.getCursorLine(); int cursorLineNumber = selection.getCursorLineNumber(); int deleteColumn = !afterCursor ? selection.getCursorColumn() - 1 : selection.getCursorColumn(); if (cursorLine.hasColumn(deleteColumn)) { getEditorDocumentMutator().deleteText(cursorLine, cursorLineNumber, deleteColumn, 1); } else if (deleteColumn < 0 && cursorLine.getPreviousLine() != null) { // Join the lines Line previousLine = cursorLine.getPreviousLine(); getEditorDocumentMutator().deleteText(previousLine, cursorLineNumber - 1, previousLine.getText().length() - 1, 1); } } public void deleteWord(boolean afterCursor) { if (tryDeleteSelection()) { return; } Line cursorLine = selection.getCursorLine(); int cursorColumn = selection.getCursorColumn(); boolean mergeWithPreviousLine = cursorColumn == 0 && !afterCursor; boolean mergeWithNextLine = cursorColumn == cursorLine.length() - 1 && afterCursor; if (mergeWithPreviousLine || mergeWithNextLine) { // Re-use delete character logic deleteCharacter(afterCursor); return; } int otherColumn = afterCursor ? TextUtils.findNextWord(cursorLine.getText(), cursorColumn, true) : TextUtils .findPreviousWord(cursorLine.getText(), cursorColumn, false); editorDocumentMutator.deleteText(cursorLine, Math.min(otherColumn, cursorColumn), Math.abs(otherColumn - cursorColumn)); } private boolean tryDeleteSelection() { if (selection.hasSelection()) { selection.deleteSelection(editorDocumentMutator); return true; } else { return false; } } ViewportModel getViewportModel() { return viewport; } public RootActionExecutor getActionExecutor() { return actionExecutor; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/InputMode.java
client/src/main/java/com/google/collide/client/editor/input/InputMode.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.util.SignalEventUtils; import com.google.collide.client.util.input.CharCodeWithModifiers; import com.google.collide.client.util.input.KeyCodeMap; import elemental.events.Event; import elemental.js.util.JsArrayOfInt; import elemental.js.util.JsMapFromIntTo; /** * Class that represents an editor mode for handling input, such as vi's insert * mode. * * <p>Each mode controls a collection of {@link Shortcut}s and fires them * based upon any input via {@link Shortcut#event}. */ public abstract class InputMode { /** * Effect of a SignalEvent. */ public enum EventResult { /** * Event would directly trigger a StreamShortcut callback. */ STREAM_CALLBACK, /** * Event is part of one or more StreamShortcuts, but has not been completely * typed. */ STREAM_PART, /** * Event would directly trigger an EventShortcut callback. */ EVENT_CALLBACK, /** * Event would not trigger an Event, or was part/all of StreamShortcut */ NONE } /** * Manager of collection of shortcuts for this class and the buffer of any * ongoing shortcut stream of keys. */ public class ShortcutController { /** * Generic Node class. * * Cannot be nested inside PartialTrie * (<a href="http://code.google.com/p/google-web-toolkit/issues/detail?id=5483">link</a>). */ private class Node<T> { T value; JsMapFromIntTo<Node<T>> next; Node() { next = JsMapFromIntTo.create(); } } //TODO: Move this functionality to AbstractTrie. /** * Basic trie class, supporting only put and get, plus a feedback function * to check if a string is along the path to a valid trie entry. * * @see #alongPath */ private class PartialTrie<T> { private Node<T> root; PartialTrie() { root = new Node<T>(); } /** * Inserts a new value T into the trie. * * @return T previous value at prefix, or null if there was no old entry */ T put(JsArrayOfInt prefix, T value) { Node<T> current = root; for (int i = 0, n = prefix.length(); i < n; i++) { int index = prefix.get(i); Node<T> next = current.next.get(index); if (next == null) { // this branch doesn't exist yet next = new Node<T>(); current.next.put(index, next); current = next; } } T old = current.value; current.value = value; return old; } /** * Returns 0 if seq is along the path to one or more entries. * * <p>For example, nearestValue("app") would return 0 for a trie with * values "apples", "apple", "orange". "apple" has 0 characters to get * to "apple". * * @return {@code 1} for direct match, {@code 0} for path match, * {@code -1} for no match */ int alongPath(JsArrayOfInt seq) { Node<T> current = root; for (int i = 0, n = seq.length(); i < n; i++) { int index = seq.get(i); current = current.next.get(index); if (current == null) { return -1; // off the end of the trie, no match } } // If we get here, current is along the path to one or more valid // entries if (current.value != null) { return 1; } else { return 0; } } /** * Returns the value T stored at exactly this location in the trie. * * @return T */ T get(JsArrayOfInt seq) { Node<T> current = root; for (int i = 0, n = seq.length(); i < n; i++) { int index = seq.get(i); current = current.next.get(index); if (current == null) { return null; } } return current.value; } } /** * Buffer of the current input stream building to a shortcut. * * <p>String is represented by an array of UTF-16 integers. * * <p>This will be appended to when the input matches a prefix of one * or more {@link StreamShortcut}s. Used to match against a PrefixTrie. */ JsArrayOfInt streamBuffer; PartialTrie<StreamShortcut> streamTrie; /** * A map of {@link EventShortcut}s from event hash to shortcut object. */ JsMapFromIntTo<EventShortcut> eventShortcuts; public ShortcutController() { eventShortcuts = JsMapFromIntTo.create(); streamTrie = new PartialTrie<StreamShortcut>(); streamBuffer = JsArrayOfInt.create(); } /** * Adds an event shortcut to the event shortcut map. */ public void addShortcut(EventShortcut event) { eventShortcuts.put(event.getKeyDigest(), event); } /** * Adds a stream shortcut to the stream shortcut trie. */ public void addShortcut(StreamShortcut stream) { streamTrie.put(stream.getActivationStream(), stream); } /** * Clears any internal state (streamBuffer value), * after shortcut was triggered. */ public void reset() { streamBuffer.setLength(0); } /** * Returns the shortcut associated with this event. */ private Shortcut findEventShortcut(SignalEvent event) { int keyDigest = CharCodeWithModifiers.computeKeyDigest(event); if (eventShortcuts.hasKey(keyDigest)) { return eventShortcuts.get(keyDigest); } else { return null; } } /** * Searches the trie using streamBuffer for an exact * {@link StreamShortcut} match. * * @return {@link StreamShortcut} if found, else {@code null} */ private Shortcut findStreamShortcut() { return streamTrie.get(streamBuffer); } /** * Adds the keycode of the event to the end of the stream buffer. */ private void addToStreamBuffer(SignalEvent event) { streamBuffer.push(KeyCodeMap.getKeyFromEvent(event)); } /** * Deletes the last character from the stream buffer (backspace). */ public void deleteLastCharFromStreamBuffer() { streamBuffer.setLength(streamBuffer.length() - 1); } /** * Tests if the event should be "captured". * * <p>Event should be captured if it either:<ul> * <li>directly fires a callback or * <li>is part of a StreamCallback that hasn't been fully typed yet * </ul> * * @return {@link EventResult} that this event would cause */ public EventResult testEventEffect(SignalEvent event) { // Letters above U+FFFF will wrap around, so they aren't supported in // shortcuts. if (event.getKeyCode() > 0xFFFF) { return EventResult.NONE; } // Try EventShortcut. int keyDigest = CharCodeWithModifiers.computeKeyDigest(event); if (eventShortcuts.hasKey(keyDigest)) { return EventResult.EVENT_CALLBACK; } // Then try StreamShortcut. addToStreamBuffer(event); int streamResult = streamTrie.alongPath(streamBuffer); // Take off event keycode - it was added only to search trie. deleteLastCharFromStreamBuffer(); if (streamResult == 1) { // Exact match. return EventResult.STREAM_CALLBACK; } else if (streamResult == 0) { // Partial match. return EventResult.STREAM_PART; } // No effect. return EventResult.NONE; } } private ShortcutController shortcutController; private InputScheme scheme = null; public InputMode() { shortcutController = new ShortcutController(); } /** * Preforms mode-specific setup (such as adding a new overlay to * display the current search term as the user types). */ public abstract void setup(); /** * Removes document changes made in {@link InputMode#setup()}. */ public abstract void teardown(); /** * Implements default behavior when no shortcut matches the input event. * * <p>Include the text captured from the hidden input field. * * @param character - 0 for no printable character * @return {@code true} to prevent default action in browser */ public abstract boolean onDefaultInput(SignalEvent signal, char character); /** * Takes action after user has inserted more than one character of text. * * @param text - more than one character * @return boolean True to prevent default action in browser */ public abstract boolean onDefaultPaste(SignalEvent signal, String text); void setScheme(InputScheme scheme) { this.scheme = scheme; } public InputScheme getScheme() { return this.scheme; } /** * Binds specified key to named action. */ public void bindAction(String actionName, int modifiers, int charCode) { shortcutController.addShortcut(new ActionShortcut(modifiers, charCode, actionName)); } /** * Adds this event shortcut to the shortcut controller. */ public void addShortcut(EventShortcut shortcut) { shortcutController.addShortcut(shortcut); } public void addShortcut(StreamShortcut shortcut) { shortcutController.addShortcut(shortcut); } /** * Checks if this event should fire any shortcuts. * * <p>There is not matching events, fires the defaultInput function. * * @return {@code true} if default browser behavior should be prevented */ public boolean handleEvent(SignalEvent event, String text) { if (event.isPasteEvent()) { String pasteContents = SignalEventUtils.getPasteContents((Event) event.asEvent()); if (pasteContents != null) { return onDefaultPaste(event, pasteContents); } } // If one character was entered, send it through the shortcut system, else // think of it as a paste. if (text.length() > 1) { return onDefaultPaste(event, text); } else { Shortcut eventShortcut = null; EventResult result = shortcutController.testEventEffect(event); if (result == EventResult.EVENT_CALLBACK) { eventShortcut = shortcutController.findEventShortcut(event); } if (result == EventResult.NONE) { shortcutController.reset(); char character = 0; if (text.length() == 1) { character = text.charAt(0); } return onDefaultInput(event, character); } if (result == EventResult.STREAM_CALLBACK || result == EventResult.STREAM_PART) { // Always add to the buffer for either of these. shortcutController.addToStreamBuffer(event); if (result == EventResult.STREAM_CALLBACK) { eventShortcut = shortcutController.findStreamShortcut(); } else { // STREAM_PART return true; // Always prevent default when adding to stream buffer. } } // Tell the shortcut controller that a shortcut was fired so it can reset // state. shortcutController.reset(); boolean returnValue = eventShortcut.event(this.scheme, event); // Only fire if the event is blocked. if (returnValue) { this.scheme.handleShortcutCalled(); } return returnValue; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/DefaultActionExecutor.java
client/src/main/java/com/google/collide/client/editor/input/DefaultActionExecutor.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.shared.util.JsonCollections; /** * Default implementation that executed actions placed in map. * */ public class DefaultActionExecutor implements ActionExecutor { private final JsonStringMap<Shortcut> actions = JsonCollections.createMap(); @Override public boolean execute(String actionName, InputScheme scheme, SignalEvent event) { Shortcut shortcut = actions.get(actionName); if (shortcut == null) { return false; } return shortcut.event(scheme, event); } protected void addAction(String actionName, Shortcut executor) { actions.put(actionName, executor); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/CommonActions.java
client/src/main/java/com/google/collide/client/editor/input/CommonActions.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; /** * Constants that define common actions. */ public class CommonActions { // TODO: 1) Refactor: extract common actions from default scheme. // TODO: 2) Create action class = name + desctiption. // TODO: 3) Make key-action binding configurable. public static final String TOGGLE_COMMENT = "toggle-comment"; public static final String GOTO_DEFINITION = "goto-definition"; public static final String GOTO_SOURCE = "goto-source"; public static final String SPLIT_LINE = "split-line"; public static final String START_NEW_LINE = "start-new-line"; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/DefaultScheme.java
client/src/main/java/com/google/collide/client/editor/input/DefaultScheme.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import java.util.Random; import org.waveprotocol.wave.client.common.util.JsoIntMap; import org.waveprotocol.wave.client.common.util.SignalEvent; import org.waveprotocol.wave.client.common.util.UserAgent; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.Spacer; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.editor.selection.SelectionModel.MoveAction; import com.google.collide.client.util.input.CharCodeWithModifiers; import com.google.collide.client.util.input.KeyCodeMap; import com.google.collide.client.util.input.ModifierKeys; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.SortedList; import elemental.events.KeyboardEvent; /** * The default InputScheme implementation for common keybindings. {@link ModifierKeys#ACTION} * for action key abstraction details. * <ul> * <li>ACTION+S - prevent default save behavior from browser. * <li>ACTION+A - select all text in the current document. * <li>TAB - if there is a selection region then insert a tab at the beginning * of each line the selection passes through, else insert a tab at the current * position. * <li>SHIFT+TAB - remove a tab character if possible from the beginning of each * line the current selection passes through. * <li>BACKSPACE - delete one character to the left of the cursor. DELETE - * delete one character to the right of the cursor. * <li>CUT (ACTION+X)/COPY (ACTION+C)/PASTE (ACTION+V) - same as native * cut/copy/paste functionality. * <li>UNDO (ACTION+Z)/REDO (ACTION+Y) - undo or redo the most recent change * to the document. * <li>Cursor movement (ARROW_*, PAGE_*) - change the position of the cursor * based upon the directional key pressed and the unit of movement associated * with that key. For arrow keys this is one character in the direction of the * arrow, for page up/down this is an entire page. * </ul> * * */ public class DefaultScheme extends InputScheme { private static final boolean ENABLE_DEBUG_SPACER_KEYS = false; private static final boolean ENABLE_ANIMATION_CONTROL_KEYS = false; static final JsoIntMap<MoveAction> MOVEMENT_KEYS_MAPPING = JsoIntMap.create(); InputMode defaultMode; static { //Initialize key mappings. registerMovementKey(ModifierKeys.NONE, KeyCodeMap.ARROW_LEFT, MoveAction.LEFT); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.ARROW_RIGHT, MoveAction.RIGHT); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.ARROW_UP, MoveAction.UP); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.ARROW_DOWN, MoveAction.DOWN); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.PAGE_UP, MoveAction.PAGE_UP); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.PAGE_DOWN, MoveAction.PAGE_DOWN); if (UserAgent.isMac()) { registerMovementKey(ModifierKeys.ALT, KeyCodeMap.ARROW_LEFT, MoveAction.WORD_LEFT); registerMovementKey(ModifierKeys.ALT, KeyCodeMap.ARROW_RIGHT, MoveAction.WORD_RIGHT); registerMovementKey(ModifierKeys.ACTION, KeyCodeMap.ARROW_LEFT, MoveAction.LINE_START); registerMovementKey(ModifierKeys.ACTION, KeyCodeMap.ARROW_RIGHT, MoveAction.LINE_END); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.HOME, MoveAction.TEXT_START); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.END, MoveAction.TEXT_END); /* * Add Emacs-style bindings on Mac (note that these will not conflict * with any Collide shortcuts since these chord with CTRL, and Collide * shortcuts chord with CMD) */ registerMovementKey(ModifierKeys.CTRL, 'a', MoveAction.LINE_START); registerMovementKey(ModifierKeys.CTRL, 'e', MoveAction.LINE_END); registerMovementKey(ModifierKeys.CTRL, 'p', MoveAction.UP); registerMovementKey(ModifierKeys.CTRL, 'n', MoveAction.DOWN); registerMovementKey(ModifierKeys.CTRL, 'f', MoveAction.RIGHT); registerMovementKey(ModifierKeys.CTRL, 'b', MoveAction.LEFT); } else { registerMovementKey(ModifierKeys.ACTION, KeyCodeMap.ARROW_LEFT, MoveAction.WORD_LEFT); registerMovementKey(ModifierKeys.ACTION, KeyCodeMap.ARROW_RIGHT, MoveAction.WORD_RIGHT); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.HOME, MoveAction.LINE_START); registerMovementKey(ModifierKeys.NONE, KeyCodeMap.END, MoveAction.LINE_END); registerMovementKey(ModifierKeys.ACTION, KeyCodeMap.HOME, MoveAction.TEXT_START); registerMovementKey(ModifierKeys.ACTION, KeyCodeMap.END, MoveAction.TEXT_END); } } private static void registerMovementKey(int modifiers, int charCode, MoveAction action) { MOVEMENT_KEYS_MAPPING.put(CharCodeWithModifiers.computeKeyDigest(modifiers, charCode), action); } /** * Setup and add single InputMode */ public DefaultScheme(InputController inputController) { super(inputController); defaultMode = new InputMode() { @Override public void setup() { } @Override public void teardown() { } /** * By default, check for cursor movement, then add this as text to the * current document. * * Only add printable text, not control characters. */ @Override public boolean onDefaultInput(SignalEvent event, char character) { // Check for movement here. int letter = KeyCodeMap.getKeyFromEvent(event); int modifiers = ModifierKeys.computeModifiers(event); boolean withShift = (modifiers & ModifierKeys.SHIFT) != 0; modifiers &= ~ModifierKeys.SHIFT; int strippedKeyDigest = CharCodeWithModifiers.computeKeyDigest(modifiers, letter); if (MOVEMENT_KEYS_MAPPING.containsKey(strippedKeyDigest)) { MoveAction action = MOVEMENT_KEYS_MAPPING.get(strippedKeyDigest); getScheme().getInputController().getSelection().move(action, withShift); return true; } if (event.getAltKey()) { // Don't process Alt+* combinations. return false; } if (event.getCommandKey() || event.getKeySignalType() != SignalEvent.KeySignalType.INPUT) { // Don't insert any Action+* / non-input combinations as text. return false; } InputController input = this.getScheme().getInputController(); SelectionModel selection = input.getSelection(); int column = selection.getCursorColumn(); if (KeyCodeMap.isPrintable(letter)) { String text = Character.toString((char) letter); // insert a single character input.getEditorDocumentMutator().insertText(selection.getCursorLine(), selection.getCursorLineNumber(), column, text); return true; } // let it fall through return false; } /** * Insert more than one character directly into the document */ @Override public boolean onDefaultPaste(SignalEvent event, String text) { SelectionModel selection = this.getScheme().getInputController().getSelection(); int column = selection.getCursorColumn(); getScheme().getInputController().getEditorDocumentMutator() .insertText(selection.getCursorLine(), selection.getCursorLineNumber(), column, text); return true; } }; /* * ACTION+S - prevent the default browser behavior because the document is * saved automatically. */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 's') { @Override public boolean event(InputScheme scheme, SignalEvent event) { // prevent ACTION+S return true; } }); /** * ACTION+A - select all text in the current document. * * @see SelectionModel#selectAll() */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'a') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().getSelection().selectAll(); return true; } }); defaultMode.bindAction(CommonActions.GOTO_DEFINITION, ModifierKeys.ACTION, 'b'); defaultMode.bindAction(CommonActions.GOTO_SOURCE, ModifierKeys.NONE, KeyCodeMap.F4); defaultMode.bindAction(CommonActions.SPLIT_LINE, ModifierKeys.ACTION, KeyCodeMap.ENTER); defaultMode.bindAction(CommonActions.START_NEW_LINE, ModifierKeys.SHIFT, KeyCodeMap.ENTER); // Single / multi-line comment / uncomment. defaultMode.bindAction(CommonActions.TOGGLE_COMMENT, ModifierKeys.ACTION, KeyboardEvent.KeyCode.SLASH); // Multi-line indenting and dedenting. /** * TAB - add a tab at the current position, or at the beginning of each line * if there is a selection. * * @see InputController#indentSelection() */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.TAB) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().handleTab(); return true; } }); /** * SHIFT+TAB - remove a tab from the beginning of each line in the * selection. * * @see InputController#dedentSelection() */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.SHIFT, KeyCodeMap.TAB) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().dedentSelection(); return true; } }); /** * BACKSPACE - native behavior * * @see InputController#deleteCharacter(boolean) */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.BACKSPACE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteCharacter(false); return true; } }); /** * SHIFT+BACKSPACE - native behavior * * @see InputController#deleteCharacter(boolean) */ // This is common due to people backspacing while typing uppercase chars defaultMode.addShortcut( new EventShortcut(ModifierKeys.SHIFT, KeyCodeMap.BACKSPACE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteCharacter(false); return true; } }); /** * ACTION+BACKSPACE - delete previous word */ defaultMode.addShortcut(new EventShortcut(wordGrainModifier(), KeyCodeMap.BACKSPACE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteWord(false); return true; } }); /** * DELETE - native behavior * * @see InputController#deleteCharacter(boolean) */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.DELETE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteCharacter(true); return true; } }); /** * ESC - Broadcasts clear message */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.NONE, KeyCodeMap.ESC) { @Override public boolean event(InputScheme scheme, SignalEvent event) { // TODO: Make this broadcast event. return true; } }); /** * ACTION+DELETE - delete next word */ defaultMode.addShortcut(new EventShortcut(wordGrainModifier(), KeyCodeMap.DELETE) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().deleteWord(true); return true; } }); /** * UNDO (ACTION+Z) - undo the most recent document action * * @see Editor#undo() */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'z') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().getEditor().undo(); return true; } }); /** * REDO (ACTION+Y) - redo the last undone document action * * @see Editor#redo() */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'y') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme.getInputController().getEditor().redo(); return true; } }); /** * Find Next (ACTION+G) - Goto next match */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'g') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme .getInputController() .getEditor() .getSearchModel() .getMatchManager() .selectNextMatch(); return true; } }); /** * Find Previous (ACTION+SHIFT+G) - Goto previous match */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'G') { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme .getInputController() .getEditor() .getSearchModel() .getMatchManager() .selectPreviousMatch(); return true; } }); /** * Move line up (ALT+Up) */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ALT, KeyCodeMap.ARROW_UP) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme .getInputController() .moveLinesUp() ; return true; } }); /** * Move line down (ALT+Down) */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ALT, KeyCodeMap.ARROW_DOWN) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme .getInputController() .moveLinesDown() ; return true; } }); /** * Clone line up (ACTION+ALT+Up) */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ALT|ModifierKeys.ACTION, KeyCodeMap.ARROW_UP) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme .getInputController() .moveLinesUp() ; return true; } }); /** * Clone line down (ACTION+ALT+Down) */ defaultMode.addShortcut(new EventShortcut(ModifierKeys.ALT|ModifierKeys.ACTION, KeyCodeMap.ARROW_DOWN) { @Override public boolean event(InputScheme scheme, SignalEvent event) { scheme .getInputController() .moveLinesDown() ; return true; } }); if (ENABLE_DEBUG_SPACER_KEYS) { final SortedList<Spacer> spacers = new SortedList<Spacer>(new Spacer.Comparator()); final Spacer.OneWaySpacerComparator spacerFinder = new Spacer.OneWaySpacerComparator(); defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'i') { @Override public boolean event(InputScheme scheme, SignalEvent event) { final Editor editor = scheme.getInputController().getEditor(); spacers.add(editor.getBuffer().addSpacer( new LineInfo(editor.getSelection().getCursorLine(), editor.getSelection() .getCursorLineNumber()), new Random().nextInt(500) + 1)); return true; } }); defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'd') { @Override public boolean event(InputScheme scheme, SignalEvent event) { final Editor editor = scheme.getInputController().getEditor(); spacerFinder.setValue(editor.getSelection().getCursorLineNumber()); int spacerIndex = spacers.findInsertionIndex(spacerFinder, false); if (spacerIndex >= 0) { editor.getBuffer().removeSpacer(spacers.get(spacerIndex)); spacers.remove(spacerIndex); } return true; } }); defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'u') { @Override public boolean event(InputScheme scheme, SignalEvent event) { final Editor editor = scheme.getInputController().getEditor(); spacerFinder.setValue(editor.getSelection().getCursorLineNumber()); int spacerIndex = spacers.findInsertionIndex(spacerFinder, false); if (spacerIndex >= 0) { // spacers.get(spacerIndex).setHeight(new Random().nextInt(500)+1); } return true; } }); } if (ENABLE_ANIMATION_CONTROL_KEYS) { defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'e') { @Override public boolean event(InputScheme scheme, SignalEvent event) { final Editor editor = scheme.getInputController().getEditor(); editor.setAnimationEnabled(true); return true; } }); defaultMode.addShortcut(new EventShortcut(ModifierKeys.ACTION, 'd') { @Override public boolean event(InputScheme scheme, SignalEvent event) { final Editor editor = scheme.getInputController().getEditor(); editor.setAnimationEnabled(false); return true; } }); } addMode(1, defaultMode); } private static int wordGrainModifier() { return UserAgent.isMac() ? ModifierKeys.ALT : ModifierKeys.ACTION; } @Override public void setup() { switchMode(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/com/google/collide/client/editor/input/ActionShortcut.java
client/src/main/java/com/google/collide/client/editor/input/ActionShortcut.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; /** * Implementation that delegates execution to action executor. */ public class ActionShortcut extends EventShortcut { private final String actionName; public ActionShortcut(int modifiers, int charCode, String actionName) { super(modifiers, charCode); this.actionName = actionName; } @Override public boolean event(InputScheme scheme, SignalEvent event) { RootActionExecutor executor = scheme.getInputController().getActionExecutor(); return executor.execute(actionName, scheme, event); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/InputScheme.java
client/src/main/java/com/google/collide/client/editor/input/InputScheme.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; import elemental.js.util.JsMapFromIntTo; /** * Controller around a group of {@link InputMode}s to direct text/modifier * key input to the active mode. Provides access to the current {@link InputController} * to the active mode for performing shortcut actions. * * Each scheme can contain additional state that needs to be shared between modes, * such as a vi line-mode search "/class", and additional command-mode next match * "n" commands * * Tied to the lifetime of an editor instance * * */ public abstract class InputScheme { /** * Store a reference to the editor's input controller to pass to active mode */ private InputController inputController; private InputMode activeMode = null; /** * Map from mode number to mode object. Mode numbers should be constants * defined for each scheme. */ private JsMapFromIntTo<InputMode> modes; public InputScheme() { this.inputController = null; this.modes = JsMapFromIntTo.create(); } public InputScheme(InputController input) { this.inputController = input; this.modes = JsMapFromIntTo.create(); } /** * Add all Scheme modes and setup the default {@link InputMode} by calling * switchMode. Optionally make any scheme-specific document changes * (add status bar, etc) */ public abstract void setup(); /** * Called when switching editor modes, this should undo all document * changes made in {@link InputScheme#setup()} */ public void teardown() { if (activeMode != null) { activeMode.teardown(); } } /** * Add a new mode to this scheme */ public void addMode(int modeNumber, InputMode mode) { mode.setScheme(this); modes.put(modeNumber, mode); } public InputController getInputController() { return inputController; } public InputMode getMode() { return activeMode; } /** * Switch to the new mode: * call teardown() on active mode (if there is one) * call setup() on new mode */ public void switchMode(int modeNumber) { if (modes.hasKey(modeNumber)) { if (activeMode != null) { activeMode.teardown(); } activeMode = modes.get(modeNumber); activeMode.setup(); } } /** * Called from the event handler, dispatch this event to the active mode */ public boolean handleEvent(SignalEvent event, String text) { if (activeMode != null) { return activeMode.handleEvent(event, text); } else { return false; } } /** * This is called after a shortcut has been dispatched. */ protected void handleShortcutCalled() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/StreamShortcut.java
client/src/main/java/com/google/collide/client/editor/input/StreamShortcut.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import elemental.js.util.JsArrayOfInt; /** * Represents a shortcut activated by a stream of text characters, such as ":q!" * * */ public abstract class StreamShortcut implements Shortcut { private JsArrayOfInt stream; /** * Constructors for passing shortcuts as ascii, integer array or JsoArray */ public StreamShortcut(String stream) { this.stream = JsArrayOfInt.create(); for (int i = 0, n = stream.length(); i < n; i++) { this.stream.set(i, stream.charAt(i)); } } /** * Return the String that causes this shortcut to be called */ public JsArrayOfInt getActivationStream() { return stream; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/EventShortcut.java
client/src/main/java/com/google/collide/client/editor/input/EventShortcut.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import com.google.collide.client.util.input.CharCodeWithModifiers; /** * EventShortcuts are fired when the combination of modifiers and charcode value * match the current SignalEvent. * */ public abstract class EventShortcut extends CharCodeWithModifiers implements Shortcut { public EventShortcut(int modifiers, int charCode) { super(modifiers, charCode); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/input/ReadOnlyScheme.java
client/src/main/java/com/google/collide/client/editor/input/ReadOnlyScheme.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.input; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.util.input.KeyCodeMap; import com.google.collide.client.util.input.ModifierKeys; /** * An input scheme to support the editor's read-only mode. */ public class ReadOnlyScheme extends InputScheme { private class ReadOnlyInputMode extends InputMode { @Override public void setup() { addShortcut(new EventShortcut(ModifierKeys.ACTION, 'a') { @Override public boolean event(InputScheme scheme, SignalEvent event) { getInputController().getSelection().selectAll(); return true; } }); } @Override public void teardown() { } @Override public boolean onDefaultInput(SignalEvent event, char character) { int key = KeyCodeMap.getKeyFromEvent(event); ViewportModel viewport = getInputController().getViewportModel(); switch (key) { case KeyCodeMap.ARROW_LEFT: case KeyCodeMap.ARROW_RIGHT: viewport.shiftHorizontally(key == KeyCodeMap.ARROW_RIGHT); return true; case KeyCodeMap.ARROW_UP: case KeyCodeMap.ARROW_DOWN: viewport.shiftVertically(key == KeyCodeMap.ARROW_DOWN, false); return true; case KeyCodeMap.PAGE_UP: case KeyCodeMap.PAGE_DOWN: viewport.shiftVertically(key == KeyCodeMap.PAGE_DOWN, true); return true; case KeyCodeMap.HOME: case KeyCodeMap.END: viewport.jumpTo(key == KeyCodeMap.END); return true; } return false; } @Override public boolean onDefaultPaste(SignalEvent signal, String text) { return false; } } public ReadOnlyScheme(InputController input) { super(input); addMode(1, new ReadOnlyInputMode()); } @Override public void setup() { switchMode(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/com/google/collide/client/editor/selection/SelectionLineRenderer.java
client/src/main/java/com/google/collide/client/editor/selection/SelectionLineRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.selection; import com.google.collide.client.editor.FocusManager; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.Position; import com.google.collide.shared.util.MathUtils; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; /** * A line renderer that styles the lines contained in the user's selection. */ public class SelectionLineRenderer implements LineRenderer { /** * CssResource for the {@link SelectionLineRenderer}. */ public interface Css extends CssResource { String selection(); String inactiveSelection(); } /** * ClientBundle for the {@link SelectionLineRenderer}. */ public interface Resources extends ClientBundle { @Source("SelectionLineRenderer.css") Css editorSelectionLineRendererCss(); } /** * Current chunk being rendered's position inside {@link #chunkLengths} and * {@link #chunkStyles} */ private int curChunkIndex; /** * Length of each chunk (there are a maximum of three chunks: beginning * non-selected text, selected text, and trailing non-selected text) */ private int[] chunkLengths = new int[3]; /** Style for each chunk */ private String[] chunkStyles = new String[3]; private final Css css; private final FocusManager focusManager; private final SelectionModel selectionModel; SelectionLineRenderer(SelectionModel selectionModel, FocusManager focusManager, Resources res) { this.focusManager = focusManager; this.css = res.editorSelectionLineRendererCss(); this.selectionModel = selectionModel; } @Override public void renderNextChunk(Target target) { target.render(chunkLengths[curChunkIndex], chunkStyles[curChunkIndex]); curChunkIndex++; } @Override public boolean resetToBeginningOfLine(Line line, int lineNumber) { if (!selectionModel.hasSelection() || !MathUtils.isInRangeInclusive(lineNumber, selectionModel.getSelectionBeginLineNumber(), selectionModel.getSelectionEndLineNumber())) { return false; } Position[] selection = selectionModel.getSelectionRange(false); /* * If this line is the first line of the selection, the column is the * selection's column. Otherwise, the column is 0 since this line is * entirely in the selection. */ int selectionBeginColumn = selection[0].getLineInfo().number() == lineNumber ? selection[0].getColumn() : 0; // Similar to above, except for the last line int selectionEndColumnExclusive = selection[1].getLineInfo().number() == lineNumber ? selection[1].getColumn() : line .getText().length(); if (selectionEndColumnExclusive == 0) { // This line doesn't actually have a selection return false; } resetChunks(line, selectionBeginColumn, selectionEndColumnExclusive); curChunkIndex = 0; return true; } @Override public boolean shouldLastChunkFillToRight() { return true; } private void resetChunks(Line line, int selectionBeginColumn, int selectionEndColumnExclusive) { int curChunkIndex = 0; if (selectionBeginColumn > 0) { /* * The selection does not start at the beginning of the line, so the first * chunk should be null */ chunkStyles[curChunkIndex] = null; chunkLengths[curChunkIndex] = selectionBeginColumn; curChunkIndex++; } chunkStyles[curChunkIndex] = focusManager.hasFocus() ? css.selection() : css.inactiveSelection(); chunkLengths[curChunkIndex] = selectionEndColumnExclusive - selectionBeginColumn; curChunkIndex++; if (selectionEndColumnExclusive < line.getText().length()) { chunkStyles[curChunkIndex] = null; chunkLengths[curChunkIndex] = line.getText().length() - selectionEndColumnExclusive; curChunkIndex++; } for (; curChunkIndex < chunkStyles.length; curChunkIndex++) { chunkStyles[curChunkIndex] = null; chunkLengths[curChunkIndex] = 0; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/selection/SelectionModel.java
client/src/main/java/com/google/collide/client/editor/selection/SelectionModel.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.selection; import static com.google.collide.shared.document.util.LineUtils.getLastCursorColumn; import static com.google.collide.shared.document.util.LineUtils.rubberbandColumn; import org.waveprotocol.wave.client.common.util.UserAgent; import com.google.collide.client.document.linedimensions.LineDimensionsCalculator.RoundingStrategy; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.ViewportModel; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.document.anchor.AnchorUtils; import com.google.collide.shared.document.anchor.InsertionPlacementStrategy; import com.google.collide.shared.document.anchor.ReadOnlyAnchor; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.document.util.PositionUtils; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.StringUtils; import com.google.collide.shared.util.TextUtils; import com.google.collide.shared.util.UnicodeUtils; import com.google.common.base.Preconditions; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.regexp.shared.RegExp; // TODO: this class is getting huge, time to split responsibilities /** * A class that models the user's selection. In addition to storing the * selection and cursor positions, this class listens for mouse drags and other * actions that affect the selection. * * The lifecycle of this class is tied to the current document. When the * document is replaced, a new instance of this class is created for the new * document. */ public class SelectionModel implements Buffer.MouseDragListener { /** * Enumeration of movement actions. */ public enum MoveAction { LEFT, RIGHT, WORD_LEFT, WORD_RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, LINE_START, LINE_END, TEXT_START, TEXT_END } private static final AnchorType SELECTION_ANCHOR_TYPE = AnchorType.create(SelectionModel.class, "selection"); /** * Listener that is called when the user's cursor changes position. */ public interface CursorListener { /** * @param isExplicitChange true if this change was a result of either the * user moving his cursor or through programatic setting, or false if * it was caused by text mutations in the document */ void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange); } /** * Listener that is called when the user changes his selection. This will not * be called if the selection's position in the document shifts * because of edits elsewhere in the document. * * Note: The selection is different from the cursor. This will not be called * if the user does not have a selection and his cursor moves. */ public interface SelectionListener { /** * @param oldSelectionRange the selection range before this selection, or * null if there was not a selection * @param newSelectionRange the new selection range, or null if there is not * a selection */ void onSelectionChange(Position[] oldSelectionRange, Position[] newSelectionRange); } private class AnchorListener implements Anchor.ShiftListener { @Override public void onAnchorShifted(Anchor anchor) { if (anchor == cursorAnchor) { preferredCursorColumn = anchor.getColumn(); } dispatchCursorChange(false); } } /** * A repeating command that continues a user's drag-based selection when the * user's mouse pointer moves outside of the editor. */ // TODO: split out MouseDragRepeater into a smaller class private class MouseDragRepeater implements RepeatingCommand { private static final int REPEAT_PERIOD_MS = 100; private int deltaX; private int deltaY; @Override public boolean execute() { // check for movement this frame if (deltaY == 0 && deltaX == 0) { return false; } LineInfo cursorLineInfo = cursorAnchor.getLineInfo(); int cursorColumn = cursorAnchor.getColumn(); int newScrollTop = buffer.getScrollTop() + deltaY; if (deltaY != 0) { int targetCursorY = deltaY < 0 ? newScrollTop : newScrollTop + buffer.getHeight(); int cursorLineNumber = buffer.convertYToLineNumber(targetCursorY, true); int actualCursorTop = buffer.convertLineNumberToY(cursorLineNumber); if (deltaY < 0 && actualCursorTop < newScrollTop && cursorLineNumber > 0) { /* * The current line is partially visible, increment so we get a fully * visible line */ cursorLineNumber++; } else if (deltaY > 0 && cursorLineNumber < document.getLastLineNumber()) { // See above cursorLineNumber--; } cursorLineInfo = document.getLineFinder().findLine(cursorLineNumber); } if (deltaX != 0) { int targetCursorX = buffer.calculateColumnLeft(cursorLineInfo.line(), cursorAnchor.getColumn()) + deltaX; cursorColumn = buffer.convertXToRoundedVisibleColumn(targetCursorX, cursorLineInfo.line()); } buffer.setScrollTop(newScrollTop); if (viewport.isLineNumberFullyVisibleInViewport(cursorLineInfo.number())) { // Only move cursor if the target line is visible inside of viewport moveCursorUsingSelectionGranularity( cursorLineInfo, buffer.convertColumnToX(cursorLineInfo.line(), cursorColumn), false); } return true; } private void schedule(int deltaX, int deltaY) { if (this.deltaX == 0 && this.deltaY == 0) { // The repeated command is not scheduled, so schedule it Scheduler.get().scheduleFixedPeriod(this, REPEAT_PERIOD_MS); } this.deltaX = deltaX; this.deltaY = deltaY; } private void cancel() { deltaX = 0; deltaY = 0; } } private enum SelectionGranularity { CHARACTER, WORD, LINE; private static SelectionGranularity forClickCount(int clickCount) { switch (clickCount) { case 1: return CHARACTER; case 2: return WORD; case 3: return LINE; default: return CHARACTER; } } } public static SelectionModel create(Document document, Buffer buffer) { ListenerRegistrar.RemoverManager removalManager = new ListenerRegistrar.RemoverManager(); SelectionModel selection = new SelectionModel(document, buffer, removalManager); removalManager.track(buffer.getMouseDragListenerRegistrar().add(selection)); return selection; } private Anchor createSelectionAnchor(Line line, int lineNumber, int column, Document document, AnchorListener anchorListener) { Anchor anchor = document.getAnchorManager().createAnchor(SELECTION_ANCHOR_TYPE, line, lineNumber, column); anchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); anchor.getShiftListenerRegistrar().add(anchorListener); return anchor; } private final AnchorListener anchorListener; /** * The anchor of the selection ("anchor" defined as "where the selection * began", not "anchor" defined in terms of document anchors). */ private final Anchor baseAnchor; private final Buffer buffer; /** The cursor of the selection */ private final Anchor cursorAnchor; private final ListenerManager<CursorListener> cursorListenerManager; private final Document document; /** * While the user is dragging, this defines the lower bound for the minimum * selection that must be selected regardless of where the user's mouse * pointer is. This should be null outside of a drag. * * For example, if the user is in word-selection mode (by double-clicking to * start the selection), the minimum selection will be the initial word that * was double-clicked. */ private Anchor minimumDragSelectionLowerBound; /** Like {@link #minimumDragSelectionLowerBound}, this defines the upper bound */ private Anchor minimumDragSelectionUpperBound; private final MouseDragRepeater mouseDragRepeater = new MouseDragRepeater(); /** * Tracks the column that the user explicitly moved to. For example, the user * moves to line 2, column 80 and then presses the up arrow. Line 1 only has * 30 columns, so it will move to column 30, but this will still be column 80 * so if the user presses the down arrow, it will take him back to column 80. */ private int preferredCursorColumn; private SelectionGranularity selectionGranularity = SelectionGranularity.CHARACTER; private final ListenerManager<SelectionListener> selectionListenerManager; private final ListenerRegistrar.RemoverManager removerManager; private ViewportModel viewport; private SelectionModel( Document document, Buffer buffer, ListenerRegistrar.RemoverManager removerManager) { this.document = document; this.buffer = buffer; this.removerManager = removerManager; anchorListener = new AnchorListener(); cursorAnchor = createSelectionAnchor(document.getFirstLine(), 0, 0, document, anchorListener); baseAnchor = createSelectionAnchor(document.getFirstLine(), 0, 0, document, anchorListener); cursorListenerManager = ListenerManager.create(); selectionListenerManager = ListenerManager.create(); } public void deleteSelection(DocumentMutator documentMutator) { Preconditions.checkState(hasSelection(), "can't delete selection when there is no selection"); Position[] selectionRange = getSelectionRange(true); /* * TODO: optimize. It's currently O(n) where n is the number of * lines, but can be O(1) with an additional delete API */ int deleteCount = LineUtils.getTextCount(selectionRange[0].getLine(), selectionRange[0].getColumn(), selectionRange[1].getLine(), selectionRange[1].getColumn()); documentMutator.deleteText(selectionRange[0].getLine(), selectionRange[0].getLineNumber(), selectionRange[0].getColumn(), deleteCount); } public void deselect() { if (!hasSelection()) { return; } Position[] oldSelectionRange = getSelectionRangeForCallback(); moveAnchor(baseAnchor, cursorAnchor.getLineInfo(), cursorAnchor.getColumn(), false); dispatchSelectionChange(oldSelectionRange); } public int getBaseColumn() { return baseAnchor.getColumn(); } public Line getBaseLine() { return baseAnchor.getLine(); } public int getBaseLineNumber() { return baseAnchor.getLineNumber(); } public int getCursorColumn() { return cursorAnchor.getColumn(); } public Line getCursorLine() { return cursorAnchor.getLine(); } public int getCursorLineNumber() { return cursorAnchor.getLineNumber(); } public ListenerRegistrar<CursorListener> getCursorListenerRegistrar() { return cursorListenerManager; } public ListenerRegistrar<SelectionListener> getSelectionListenerRegistrar() { return selectionListenerManager; } // TODO: I think we should introduce SelectionRange bean. /** * Returns the selection range where position[0] is always the logical start * of selection and position[1] is always the logical end. * * @param inclusiveEnd true for the returned position[1] to be the last * character in the selection, false for position[1] to be the * character after the last character in the selection. If true there * must currently be a selection. */ public Position[] getSelectionRange(boolean inclusiveEnd) { Preconditions.checkArgument( hasSelection() || !inclusiveEnd, "There must be a selection if inclusiveEnd is requested."); Position[] selection = new Position[2]; Anchor beginAnchor = getEarlierSelectionAnchor(); Anchor endAnchor = getLaterSelectionAnchor(); selection[0] = new Position(beginAnchor.getLineInfo(), beginAnchor.getColumn()); if (inclusiveEnd) { Preconditions.checkState(hasSelection(), "Can't get selection range inclusive end when nothing is selected"); selection[1] = PositionUtils.getPosition(endAnchor.getLine(), endAnchor.getLineNumber(), endAnchor.getColumn(), -1); } else { selection[1] = new Position(endAnchor.getLineInfo(), endAnchor.getColumn()); } return selection; } public int getSelectionBeginLineNumber() { return isCursorAtEndOfSelection() ? baseAnchor.getLineNumber() : cursorAnchor.getLineNumber(); } public int getSelectionEndLineNumber() { return isCursorAtEndOfSelection() ? cursorAnchor.getLineNumber() : baseAnchor.getLineNumber(); } public boolean hasSelection() { return AnchorUtils.compare(cursorAnchor, baseAnchor) != 0; } public String getSelectedText() { if (!hasSelection()) { return ""; } Position[] selectionRange = getSelectionRange(true); return LineUtils.getText(selectionRange[0].getLine(), selectionRange[0].getColumn(), selectionRange[1].getLine(), selectionRange[1].getColumn()); } /** * Returns true if the selection spans a newline character. */ public boolean hasMultilineSelection() { return cursorAnchor.getLine() != baseAnchor.getLine(); } public boolean isCursorAtEndOfSelection() { return AnchorUtils.compare(cursorAnchor, baseAnchor) >= 0; } /** * Performs specified movement action. */ public void move(MoveAction action, boolean isShiftHeld) { boolean shouldUpdatePreferredColumn = true; int column = cursorAnchor.getColumn(); LineInfo lineInfo = cursorAnchor.getLineInfo(); String lineText = lineInfo.line().getText(); switch (action) { case LEFT: column = TextUtils.findPreviousNonMarkNorOtherCharacter(lineText, column); break; case RIGHT: column = TextUtils.findNonMarkNorOtherCharacter(lineText, column); break; case WORD_LEFT: column = TextUtils.findPreviousWord(lineText, column, false); /** * {@link TextUtils#findNextWord} can return line length indicating it's * at the end of a word on the line. If this line ends in a* {@code \n} * that will cause us to move to the next line when we check * {@link LineUtils#getLastCursorColumn} which isn't what we want. So * fix it now in case the lines ends in {@code \n}. */ if (column == lineInfo.line().length()) { column = rubberbandColumn(lineInfo.line(), column); } break; case WORD_RIGHT: column = TextUtils.findNextWord(lineText, column, true); /** * {@link TextUtils#findNextWord} can return line length indicating it's * at the end of a word on the line. If this line ends in a* {@code \n} * that will cause us to move to the next line when we check * {@link LineUtils#getLastCursorColumn} which isn't what we want. So * fix it now in case the lines ends in {@code \n}. */ if (column == lineInfo.line().length()) { column = rubberbandColumn(lineInfo.line(), column); } break; case UP: column = preferredCursorColumn; if (lineInfo.line() == document.getFirstLine() && (isShiftHeld || UserAgent.isMac())) { /* * Pressing up on the first line should: * - On Mac, always go to first column, or * - On all platforms, shift+up should select to first column */ column = 0; } else { lineInfo.moveToPrevious(); } column = rubberbandColumn(lineInfo.line(), column); shouldUpdatePreferredColumn = false; break; case DOWN: column = preferredCursorColumn; if (lineInfo.line() == document.getLastLine() && (isShiftHeld || UserAgent.isMac())) { // Consistent with up-arrowing on first line column = LineUtils.getLastCursorColumn(lineInfo.line()); } else { lineInfo.moveToNext(); } column = rubberbandColumn(lineInfo.line(), column); shouldUpdatePreferredColumn = false; break; case PAGE_UP: for (int i = buffer.getFlooredHeightInLines(); i > 0; i--) { lineInfo.moveToPrevious(); } column = rubberbandColumn(lineInfo.line(), preferredCursorColumn); shouldUpdatePreferredColumn = false; break; case PAGE_DOWN: for (int i = buffer.getFlooredHeightInLines(); i > 0; i--) { lineInfo.moveToNext(); } column = rubberbandColumn(lineInfo.line(), preferredCursorColumn); shouldUpdatePreferredColumn = false; break; case LINE_START: int firstNonWhitespaceColumn = TextUtils.countWhitespacesAtTheBeginningOfLine( lineInfo.line().getText()); column = (column != firstNonWhitespaceColumn) ? firstNonWhitespaceColumn : 0; break; case LINE_END: column = LineUtils.getLastCursorColumn(lineInfo.line()); break; case TEXT_START: lineInfo = new LineInfo(document.getFirstLine(), 0); column = 0; break; case TEXT_END: lineInfo = new LineInfo(document.getLastLine(), document.getLineCount() - 1); column = LineUtils.getLastCursorColumn(lineInfo.line()); break; } if (column < 0) { if (lineInfo.moveToPrevious()) { column = getLastCursorColumn(lineInfo.line()); } else { column = 0; } } else if (column > getLastCursorColumn(lineInfo.line())) { if (lineInfo.moveToNext()) { column = LineUtils.getFirstCursorColumn(lineInfo.line()); } else { column = rubberbandColumn(lineInfo.line(), column); } } moveCursor(lineInfo, column, shouldUpdatePreferredColumn, isShiftHeld, getSelectionRangeForCallback()); } @Override public void onMouseClick(Buffer buffer, int clickCount, int x, int y, boolean isShiftHeld) { int lineNumber = buffer.convertYToLineNumber(y, true); LineInfo newLineInfo = buffer.getDocument().getLineFinder().findLine(cursorAnchor.getLineInfo(), lineNumber); int newColumn = buffer.convertXToRoundedVisibleColumn(x, newLineInfo.line()); // Allow the user to keep clicking to iterate through selection modes clickCount = (clickCount - 1) % 3 + 1; selectionGranularity = SelectionGranularity.forClickCount(clickCount); if (clickCount == 1) { moveCursor(newLineInfo, newColumn, true, isShiftHeld, getSelectionRangeForCallback()); } else { setInitialSelectionForGranularity(newLineInfo, newColumn, x); } } private void setInitialSelectionForGranularity(LineInfo lineInfo, int column, int x) { /* * If the given column is more the line's length (for example, when appending to the last line * of the doc), then just assume no initial selection (since most of that calculation code * relies on getting the out-of-bounds character). */ int lineTextLength = lineInfo.line().getText().length(); if (column >= lineTextLength) { moveCursor(lineInfo, lineTextLength, true, false, getSelectionRangeForCallback()); } else if (selectionGranularity == SelectionGranularity.WORD) { Line line = lineInfo.line(); String text = line.getText(); if (UnicodeUtils.isWhitespace(text.charAt(column))) { moveCursor(lineInfo, column, true, false, getSelectionRangeForCallback()); } else { // Start seeking from the next column so the character under cursor // will belong to the "previous word". int nextColumn = column + 1; int wordStartColumn = TextUtils.findPreviousWord(text, nextColumn, false); wordStartColumn = LineUtils.rubberbandColumn(line, wordStartColumn); moveAnchor(baseAnchor, lineInfo, wordStartColumn, false); moveCursorUsingSelectionGranularity(lineInfo, x, false); } } else if (selectionGranularity == SelectionGranularity.LINE) { moveAnchor(baseAnchor, lineInfo, 0, false); moveCursorUsingSelectionGranularity(lineInfo, x, false); } } @Override public void onMouseDrag(Buffer buffer, int x, int y) { /* * The click callback sets up the initial selection, this will become the * minimum selection */ ensureMinimumDragSelectionFromCurrentSelection(); int lineNumber = buffer.convertYToLineNumber(y, true); LineInfo newLineInfo = document.getLineFinder().findLine(cursorAnchor.getLineInfo(), lineNumber); // Only move the cursor if (viewport.isLineNumberFullyVisibleInViewport(newLineInfo.number())) { moveCursorUsingSelectionGranularity(newLineInfo, x, false); } manageRepeaterForDrag(x, y); } private void ensureMinimumDragSelectionFromCurrentSelection() { if (minimumDragSelectionLowerBound != null) { return; } Position[] selectionRange = getSelectionRange(false); minimumDragSelectionLowerBound = createAnchorFromPosition(selectionRange[0]); minimumDragSelectionUpperBound = createAnchorFromPosition(selectionRange[1]); } private Anchor createAnchorFromPosition(Position position) { return document.getAnchorManager().createAnchor(SELECTION_ANCHOR_TYPE, position.getLine(), position.getLineInfo().number(), position.getColumn()); } private void removeMinimumDragSelection() { if (minimumDragSelectionLowerBound == null) { return; } document.getAnchorManager().removeAnchor(minimumDragSelectionLowerBound); document.getAnchorManager().removeAnchor(minimumDragSelectionUpperBound); minimumDragSelectionLowerBound = minimumDragSelectionUpperBound = null; } /** * Moves the cursor in the general direction of the {@code targetColumn}, but * since this takes into account the {@link #selectionGranularity}, the actual * column may be different. * * @param targetLineInfo the cursor will (mostly) stay within this line. Most * callers will give the line underneath the mouse pointer as this * parameter. (The cursor may move to the next line if the selection * granularity is line.) */ @SuppressWarnings("incomplete-switch") private void moveCursorUsingSelectionGranularity(LineInfo targetLineInfo, int x, boolean updatePreferredColumn) { Line targetLine = targetLineInfo.line(); int roundedTargetColumn = buffer.convertXToRoundedVisibleColumn(x, targetLine); // Forward if the cursor anchor will be ahead of the base anchor boolean growForward = AnchorUtils.compare(baseAnchor, targetLineInfo.number(), roundedTargetColumn) <= 0; LineInfo newLineInfo = targetLineInfo; int newColumn = roundedTargetColumn; switch (selectionGranularity) { case WORD: if (growForward) { /* * Floor the column so the last pixel of the last character of the * current word does not trigger a finding of the next word */ newColumn = TextUtils.findNextWord( targetLine.getText(), buffer.convertXToColumn(x, targetLine, RoundingStrategy.FLOOR), false); } else { // See note above about flooring, but we ceil here instead newColumn = TextUtils.findPreviousWord( targetLine.getText(), buffer.convertXToColumn(x, targetLine, RoundingStrategy.CEIL), false); } break; case LINE: // The cursor is on column 0 regardless newColumn = 0; if (growForward) { // If growing forward, move to the next line, if possible newLineInfo = targetLineInfo.copy(); if (!newLineInfo.moveToNext()) { /* * There isn't a next line, so just move the cursor to the end of * line */ newColumn = LineUtils.getLastCursorColumn(newLineInfo.line()); } } break; } Position[] oldSelectionRange = getSelectionRangeForCallback(); newColumn = LineUtils.rubberbandColumn(newLineInfo.line(), newColumn); ensureNewSelectionObeysMinimumDragSelection(newLineInfo, newColumn); moveCursor(newLineInfo, newColumn, updatePreferredColumn, true, oldSelectionRange); } private void ensureNewSelectionObeysMinimumDragSelection(LineInfo newCursorLineInfo, int newCursorColumn) { if (minimumDragSelectionLowerBound == null || AnchorUtils.compare(minimumDragSelectionLowerBound, minimumDragSelectionUpperBound) == 0) { // There isn't a minimum drag selection set return; } // Is the new selection growing forward? boolean newGrowForward = AnchorUtils.compare(baseAnchor, newCursorLineInfo.number(), newCursorColumn) <= 0; boolean newSelectionIsAheadOfMinimum = newGrowForward && AnchorUtils.compare(baseAnchor, minimumDragSelectionUpperBound) >= 0; boolean newSelectionIsBehindMinimum = !newGrowForward && AnchorUtils.compare(baseAnchor, minimumDragSelectionLowerBound) <= 0; // Move base anchor to correct minimum selection bound Anchor newBaseAnchorPosition = null; if (newSelectionIsBehindMinimum) { newBaseAnchorPosition = minimumDragSelectionUpperBound; } else if (newSelectionIsAheadOfMinimum) { newBaseAnchorPosition = minimumDragSelectionLowerBound; } if (newBaseAnchorPosition != null) { moveAnchor(baseAnchor, newBaseAnchorPosition.getLineInfo(), newBaseAnchorPosition.getColumn(), false); } } private void manageRepeaterForDrag(int x, int y) { int bufferScrollLeft = buffer.getScrollLeft(); int bufferScrollTop = buffer.getScrollTop(); int bufferHeight = buffer.getHeight(); int bufferWidth = buffer.getWidth(); int deltaX = 0; int deltaY = 0; if (y - bufferScrollTop < 0) { deltaY = y - bufferScrollTop; } else if (y >= bufferScrollTop + bufferHeight) { deltaY = y - (bufferScrollTop + bufferHeight); } if (x - bufferScrollLeft < 0) { deltaX = x - bufferScrollLeft; } else if (x >= bufferScrollLeft + bufferWidth) { deltaX = x - (bufferScrollLeft + bufferWidth); } if (deltaX == 0 && deltaY == 0) { mouseDragRepeater.cancel(); } else { mouseDragRepeater.schedule(deltaX, deltaY); } } @Override public void onMouseDragRelease(Buffer buffer, int x, int y) { mouseDragRepeater.cancel(); removeMinimumDragSelection(); } public void setSelection(LineInfo baseLineInfo, int baseColumn, LineInfo cursorLineInfo, int cursorColumn) { Preconditions.checkArgument(baseColumn <= LineUtils.getLastCursorColumn(baseLineInfo.line()), "The base column is out-of-bounds"); int lastCursorColumn = LineUtils.getLastCursorColumn(cursorLineInfo.line()); Preconditions.checkArgument(cursorColumn <= lastCursorColumn, "The cursor column is out-of-bounds. Expected <= " + lastCursorColumn + ", got " + cursorColumn + ", line " + cursorLineInfo.number()); baseColumn = LineUtils.rubberbandColumn(baseLineInfo.line(), baseColumn); cursorColumn = LineUtils.rubberbandColumn(cursorLineInfo.line(), cursorColumn); Position[] oldSelectionRange = getSelectionRangeForCallback(); moveAnchor(baseAnchor, baseLineInfo, baseColumn, false); boolean hasSelection = LineUtils.comparePositions(cursorLineInfo.number(), cursorColumn, baseLineInfo.number(), baseColumn) != 0; moveCursor(cursorLineInfo, cursorColumn, true, hasSelection, oldSelectionRange); } public void setCursorPosition(LineInfo lineInfo, int column) { int lastCursorColumn = LineUtils.getLastCursorColumn(lineInfo.line()); Preconditions.checkArgument(column <= lastCursorColumn, "The cursor column is out-of-bounds. Expected <= " + lastCursorColumn + ", got " + column + ", line " + lineInfo.number()); moveCursor(lineInfo, column, true, hasSelection(), getSelectionRangeForCallback()); } public void selectAll() { Position[] oldSelectionRange = getSelectionRangeForCallback(); moveAnchor(baseAnchor, new LineInfo(document.getFirstLine(), 0), 0, false); moveCursor(new LineInfo(document.getLastLine(), document.getLastLineNumber()), LineUtils.getLastCursorColumn(document.getLastLine()), true, true, oldSelectionRange); } public void teardown() { removerManager.remove(); if (baseAnchor != cursorAnchor) { document.getAnchorManager().removeAnchor(baseAnchor); } } public ReadOnlyAnchor getCursorAnchor() { return cursorAnchor; } public Position getCursorPosition() { return new Position(cursorAnchor.getLineInfo(), cursorAnchor.getColumn()); } private void dispatchCursorChange(final boolean isExplicitChange) { cursorListenerManager.dispatch(new Dispatcher<SelectionModel.CursorListener>() { @Override public void dispatch(CursorListener listener) { listener.onCursorChange(cursorAnchor.getLineInfo(), cursorAnchor.getColumn(), isExplicitChange); } }); } private void dispatchSelectionChange(final Position[] oldSelectionRange) { selectionListenerManager.dispatch(new Dispatcher<SelectionModel.SelectionListener>() { @Override public void dispatch(SelectionListener listener) { listener.onSelectionChange(oldSelectionRange, getSelectionRangeForCallback()); } }); } private Position[] getSelectionRangeForCallback() { return hasSelection() ? getSelectionRange(true) : null; } /** * Moves the cursor and potentially the base. This method will dispatch the * appropriate callbacks. * * @param lineInfo the line where the cursor will be positioned * @param column the column (on the given line) where the cursor will be * positioned * @param updatePreferredColumn see {@link #preferredCursorColumn} * @param isSelecting false to ensure there is not a selection after the * movement * @param oldSelectionRange the selection range (via * {@link #getSelectionRangeForCallback()}) before the caller modified * the selection. This will be passed to the selection callback as the * old selection range. */ private void moveCursor(LineInfo lineInfo, int column, boolean updatePreferredColumn, boolean isSelecting, Position[] oldSelectionRange) { boolean hadSelection = hasSelection(); // Check if base anchor should move if (!isSelecting) { moveAnchor(baseAnchor, lineInfo, column, false); } // Move cursor anchor moveAnchor(cursorAnchor, lineInfo, column, updatePreferredColumn); boolean willHaveSelection = hasSelection(); dispatchCursorChange(true); if (isSelecting || willHaveSelection != hadSelection) { dispatchSelectionChange(oldSelectionRange); } } private void moveAnchor(Anchor anchor, LineInfo lineInfo, int column, boolean updatePreferredColumn) { if (anchor.getLine().equals(lineInfo.line()) && anchor.getColumn() == column) { return; } if (updatePreferredColumn) { preferredCursorColumn = column; } document.getAnchorManager().moveAnchor(anchor, lineInfo.line(), lineInfo.number(), column); } public void initialize(ViewportModel viewport) { this.viewport = viewport; } /**
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/com/google/collide/client/editor/selection/LocalCursorController.java
client/src/main/java/com/google/collide/client/editor/selection/LocalCursorController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.selection; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.Editor.ReadOnlyListener; import com.google.collide.client.editor.FocusManager; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; /** * A controller responsible for keeping the local user's cursor renderer * up-to-date. * */ public class LocalCursorController implements SelectionModel.CursorListener, FocusManager.FocusListener, ReadOnlyListener { public static LocalCursorController create(CursorView.Resources resources, FocusManager focusManager, SelectionModel selectionModel, Buffer buffer, Editor editor) { CursorView cursorView = CursorView.create(resources, true); return new LocalCursorController(focusManager, selectionModel, cursorView, buffer, editor); } private final Buffer buffer; private final CursorView cursorView; private final JsonArray<ListenerRegistrar.Remover> listenerRemovers = JsonCollections.createArray(); private final SelectionModel selectionModel; private LocalCursorController(FocusManager focusManager, SelectionModel selectionModel, CursorView cursorView, Buffer buffer, Editor editor) { this.selectionModel = selectionModel; this.cursorView = cursorView; this.buffer = buffer; resetCursorView(); listenerRemovers.add(focusManager.getFocusListenerRegistrar().add(this)); listenerRemovers.add(selectionModel.getCursorListenerRegistrar().add(this)); listenerRemovers.add(editor.getReadOnlyListenerRegistrar().add(this)); attachCursorElement(); onFocusChange(focusManager.hasFocus()); onReadOnlyChanged(editor.isReadOnly()); } private void attachCursorElement() { buffer.addAnchoredElement(selectionModel.getCursorAnchor(), cursorView.getView().getElement()); } private void detachCursorElement() { buffer.removeAnchoredElement(selectionModel.getCursorAnchor(), cursorView.getView() .getElement()); } @Override public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) { cursorView.forceSolidBlinkState(); } @Override public void onFocusChange(boolean hasFocus) { cursorView.setVisibility(hasFocus); } @Override public void onReadOnlyChanged(boolean isReadOnly) { if (isReadOnly) { detachCursorElement(); } else { attachCursorElement(); } } public void resetCursorView() { cursorView.setColor("black"); cursorView.setBlockMode(false); } /** * TODO: let block mode use and set the color of the * character beneath it to create an inverted color effect. */ public void setBlockMode(boolean enabled) { cursorView.setBlockMode(enabled); } public void setColor(String color) { cursorView.setColor(color); } public void teardown() { for (int i = 0, n = listenerRemovers.size(); i < n; i++) { listenerRemovers.get(i).remove(); } detachCursorElement(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/selection/ToggleCommentsController.java
client/src/main/java/com/google/collide/client/editor/selection/ToggleCommentsController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.selection; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.document.Position; import com.google.common.base.Preconditions; import com.google.gwt.regexp.shared.RegExp; /** * Utility that comments / uncomments selected lines. * */ public class ToggleCommentsController { private final RegExp commentChecker; private final String commentHead; ToggleCommentsController(RegExp commentChecker, String commentHead) { this.commentChecker = commentChecker; this.commentHead = commentHead; } void processLines(DocumentMutator documentMutator, SelectionModel selection) { boolean moveDown = !selection.hasSelection(); Position[] selectionRange = selection.getSelectionRange(false); int initialColumn = selectionRange[0].getColumn(); Line terminator = selectionRange[1].getLine(); if (selectionRange[1].getColumn() != 0 || !selection.hasSelection()) { terminator = terminator.getNextLine(); } int lineNumber = selectionRange[0].getLineNumber(); Line current = selectionRange[0].getLine(); if (canUncommentAll(current, terminator)) { int headLength = commentHead.length(); while (current != terminator) { int pos = current.getText().indexOf(commentHead); documentMutator.deleteText(current, lineNumber, pos, headLength); lineNumber++; current = current.getNextLine(); } } else { while (current != terminator) { documentMutator.insertText(current, lineNumber, 0, commentHead, false); lineNumber++; current = current.getNextLine(); } } if (moveDown) { moveCursorDown(selection, initialColumn); } } /** * Check that all lines between begin (inclusive) and end (exclusive) are * commented. * * @param end {@code null} to check to document end */ private boolean canUncommentAll(Line begin, Line end) { Line current = begin; while (current != end) { Preconditions.checkNotNull(current, "hasn't met terminator before document end"); if (!commentChecker.test(current.getText())) { return false; } current = current.getNextLine(); } return true; } private void moveCursorDown(SelectionModel selection, int initialColumn) { Line line = selection.getCursorLine().getNextLine(); if (line == null) { return; } int lineNumber = selection.getCursorLineNumber() + 1; String text = line.getText(); int lineLength = text.length(); if (text.endsWith("\n")) { lineLength--; } int column = Math.min(initialColumn, lineLength); selection.setCursorPosition(new LineInfo(line, lineNumber), column); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/selection/CursorView.java
client/src/main/java/com/google/collide/client/editor/selection/CursorView.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.selection; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.user.client.Timer; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; /** * A presenter and anchor renderer for a cursor. */ public class CursorView extends UiComponent<CursorView.View> { /** * Static factory method for obtaining an instance of the CursorView. */ public static CursorView create(CursorView.Resources res, boolean isLocal) { View view = new View(res, isLocal); return new CursorView(view, isLocal); } public interface Css extends CssResource { String caret(); String root(); String block(); } public interface Resources extends ClientBundle { @Source({"CursorView.css", "com/google/collide/client/editor/constants.css"}) Css workspaceEditorCursorCss(); } static class View extends CompositeView<ViewEvents> { private final Css css; private Element caret; private View(Resources res, boolean isLocal) { this.css = res.workspaceEditorCursorCss(); setElement(createElement(isLocal)); } private Element createElement(boolean isLocal) { caret = Elements.createDivElement(css.caret()); Element root = Elements.createDivElement(css.root()); root.appendChild(caret); root.getStyle().setZIndex(isLocal ? 1 : 0); return root; } private boolean isCaretVisible() { return caret.getStyle().getVisibility().equals(CSSStyleDeclaration.Visibility.VISIBLE); } private void setCaretVisible(boolean visible) { caret.getStyle().setVisibility( visible ? CSSStyleDeclaration.Visibility.VISIBLE : CSSStyleDeclaration.Visibility.HIDDEN); } private void setColor(String color) { caret.getStyle().setBackgroundColor(color); } private void setBlockMode(boolean isBlockMode) { if (isBlockMode) { caret.addClassName(css.block()); } else { caret.removeClassName(css.block()); } } } interface ViewEvents { // TODO: onHover, so we can show the label } private static final int CARET_BLINK_PERIOD_MS = 500; private final Timer caretBlinker = new Timer() { @Override public void run() { getView().setCaretVisible(!getView().isCaretVisible()); } }; private final boolean isLocal; private boolean isVisible = true; private CursorView(View view, boolean isLocal) { super(view); this.isLocal = isLocal; } public Element getElement() { return getView().getElement(); } public void setVisibility(boolean isVisible) { this.isVisible = isVisible; /* * Use display-based visibility since visibility-based visibility is used * for blinking */ CssUtils.setDisplayVisibility2(getView().getElement(), isVisible); if (isLocal) { // Blink the local cursor if (isVisible) { caretBlinker.scheduleRepeating(CARET_BLINK_PERIOD_MS); } else { caretBlinker.cancel(); } } } public boolean isVisible() { return isVisible; } public void setColor(String color) { getView().setColor(color); } /** * @param isBlockMode If true, change the cursor into a block that covers the entire * character. */ public void setBlockMode(boolean isBlockMode) { getView().setBlockMode(isBlockMode); } void forceSolidBlinkState() { if (!isLocal) { return; } getView().setCaretVisible(true); caretBlinker.scheduleRepeating(CARET_BLINK_PERIOD_MS); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/selection/SelectionManager.java
client/src/main/java/com/google/collide/client/editor/selection/SelectionManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.selection; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.FocusManager; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.shared.document.Document; /* * TODO: split SelectionModel into multiple components owned by * this class */ /** * Manages and owns different components related to text selection. */ public class SelectionManager { public static SelectionManager create(Document document, Buffer buffer, FocusManager focusManager, SelectionLineRenderer.Resources resources) { SelectionModel selectionModel = SelectionModel.create(document, buffer); SelectionLineRenderer selectionLineRenderer = new SelectionLineRenderer(selectionModel, focusManager, resources); return new SelectionManager(selectionModel, selectionLineRenderer); } private Renderer renderer; private final SelectionLineRenderer selectionLineRenderer; private final SelectionModel selectionModel; private SelectionManager(SelectionModel selectionModel, SelectionLineRenderer selectionLineRenderer) { this.selectionModel = selectionModel; this.selectionLineRenderer = selectionLineRenderer; } public void initialize(Renderer renderer) { this.renderer = renderer; renderer.addLineRenderer(selectionLineRenderer); } public void teardown() { renderer.removeLineRenderer(selectionLineRenderer); selectionModel.teardown(); } public SelectionModel getSelectionModel() { return selectionModel; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/gutter/Gutter.java
client/src/main/java/com/google/collide/client/editor/gutter/Gutter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.gutter; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.ElementManager; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.mvp.UiComponent; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.util.ListenerManager; import com.google.collide.shared.util.ListenerManager.Dispatcher; import com.google.collide.shared.util.ListenerRegistrar; import elemental.dom.Element; /** * A gutter is a slim vertical region adjacent to the text buffer of the editor. * For example, line numbers are placed in a gutter to the left of the text * buffer. * * Overview mode is for gutters that typically are adjacent to the scrollbar. * These gutters do not have a one-to-one pixel mapping with the document, * instead the entire height of the gutter corresponds to the entire height of * the document. These are used to show an overview of some document state * independent of the editor's viewport, such as error markers or search * results. */ public class Gutter extends UiComponent<GutterView> { /** * @see Editor#createGutter(boolean, Position, String) */ public static Gutter create(boolean overviewMode, Position position, String cssClassName, Buffer buffer) { // TODO: remove when implemented if (overviewMode) { throw new IllegalArgumentException("Overview mode is not implemented yet"); } GutterView view = new GutterView(overviewMode, position, cssClassName, buffer); return new Gutter(overviewMode, view, buffer); } /** Defines which side of the editor the gutter will be placed */ public enum Position { LEFT, RIGHT } /** * A listener that is called when there is a click in the gutter. */ public interface ClickListener { void onClick(int y); } interface ViewDelegate { void onClick(int gutterY); } private final ListenerManager<ClickListener> clickListenerManager = ListenerManager.create(); private final ElementManager elementManager; private final boolean overviewMode; private Gutter(boolean overviewMode, GutterView gutterView, Buffer buffer) { super(gutterView); this.overviewMode = overviewMode; elementManager = new ElementManager(getView().contentElement, buffer); gutterView.setDelegate(new ViewDelegate() { @Override public void onClick(final int gutterY) { clickListenerManager.dispatch(new Dispatcher<Gutter.ClickListener>() { @Override public void dispatch(ClickListener listener) { listener.onClick(convertGutterYToY(gutterY)); } }); } }); } public void addAnchoredElement(Anchor anchor, Element element) { elementManager.addAnchoredElement(anchor, element); } public void removeAnchoredElement(Anchor anchor, Element element) { elementManager.removeAnchoredElement(anchor, element); } public void addUnmanagedElement(Element element) { elementManager.addUnmanagedElement(element); } public void removeUnmanagedElement(Element element) { elementManager.removeUnmanagedElement(element); } public Element getGutterElement() { return getView().getElement(); } public int getWidth() { return getView().getWidth(); } public void setWidth(int width) { getView().setWidth(width); } public ListenerRegistrar<ClickListener> getClickListenerRegistrar() { return clickListenerManager; } // not editor-public public void handleDocumentChanged(ViewportModel viewport, Renderer renderer) { getView().reset(); elementManager.handleDocumentChanged(viewport, renderer); } private int convertYToGutterY(int y) { // TODO: implement overview mode return y; } private int convertGutterYToY(int gutterY) { // TODO: implement overview mode return gutterY; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/gutter/LeftGutterManager.java
client/src/main/java/com/google/collide/client/editor/gutter/LeftGutterManager.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.gutter; import com.google.collide.client.editor.Buffer; import com.google.collide.shared.document.Document; import com.google.collide.shared.util.ListenerRegistrar.Remover; public class LeftGutterManager { private final Buffer buffer; private Document document; private Document.LineCountListener lineCountListener = new Document.LineCountListener() { @Override public void onLineCountChanged(Document document, int lineCount) { updateWidthFromLineCount(lineCount); } }; private final Gutter gutter; private Remover lineCountListenerRemover; public LeftGutterManager(Gutter gutter, Buffer buffer) { this.buffer = buffer; this.gutter = gutter; } public Gutter getGutter() { return gutter; } public void handleDocumentChanged(Document newDocument) { if (lineCountListenerRemover != null) { lineCountListenerRemover.remove(); } this.document = newDocument; lineCountListenerRemover = document.getLineCountListenerRegistrar().add(lineCountListener); updateWidthFromLineCount(document.getLineCount()); } private void updateWidthFromLineCount(int lineCount) { /* * We want to know how many digits are in the current line count (hence the * log) */ int width = (int) (((float) Math.log10(lineCount) + 1) * buffer.getEditorCharacterWidth()); gutter.setWidth(width); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/gutter/GutterView.java
client/src/main/java/com/google/collide/client/editor/gutter/GutterView.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.gutter; import collide.client.util.Elements; import com.google.collide.client.editor.Buffer; import com.google.collide.client.editor.gutter.Gutter.Position; import com.google.collide.client.editor.gutter.Gutter.ViewDelegate; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.client.util.dom.MouseGestureListener; import com.google.collide.client.util.dom.ScrollbarSizeCalculator; import com.google.collide.mvp.CompositeView; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.MouseEvent; /** * The view component of the MVP stack for a gutter. * */ class GutterView extends CompositeView<ViewDelegate> { Element contentElement; private final boolean overviewMode; Element scrollableElement; GutterView(boolean overviewMode, Position position, String cssClassName, Buffer buffer) { this.overviewMode = overviewMode; createDom(position, cssClassName); attachEventHandlers(buffer); } private void createDom(Position position, String cssClassName) { contentElement = Elements.createDivElement(); contentElement.getStyle().setPosition(CSSStyleDeclaration.Position.RELATIVE); scrollableElement = Elements.createDivElement(cssClassName); // TODO: push into elemental scrollableElement.getStyle().setProperty("float", position == Gutter.Position.LEFT ? "left" : "right"); scrollableElement.appendChild(contentElement); setElement(scrollableElement); } private void attachEventHandlers(final Buffer buffer) { // TODO: Detach listener in appropriate moment. MouseGestureListener.createAndAttach(scrollableElement, new MouseGestureListener.Callback() { @Override public boolean onClick(int clickCount, MouseEvent event) { if (clickCount != 1 || event.getButton() != MouseEvent.Button.PRIMARY) { return true; } int clickClientY = event.getClientY(); int scrollableElementClientTop = DomUtils.calculateElementClientOffset(scrollableElement).top; int gutterY = clickClientY - scrollableElementClientTop + buffer.getScrollTop(); getDelegate().onClick(gutterY); return true; } @Override public void onDrag(MouseEvent event) { // Do nothing. } @Override public void onDragRelease(MouseEvent event) { // Do nothing. } }); if (!overviewMode) { buffer.getScrollListenerRegistrar().add(new Buffer.ScrollListener() { @Override public void onScroll(Buffer buffer, int scrollTop) { // no scrollTop on unscrollable elements contentElement.getStyle().setMarginTop(-scrollTop, CSSStyleDeclaration.Unit.PX); } }); buffer.getHeightListenerRegistrar().add(new Buffer.HeightListener() { @Override public void onHeightChanged(int height) { /* * The gutter's height must account for a potential horizontal * scrollbar visible in the buffer. One example of this requirement is * the line number gutter: If the buffer is showing a horizontal * scrollbar, the last line number should be positioned the scrollbar * height from the bottom edge. So, the left gutter's scroll height * must have at least the scrollbar's height in addition to the * regular buffer scroll height. */ contentElement.getStyle().setHeight( height + ScrollbarSizeCalculator.INSTANCE.getHeightOfHorizontalScrollbar(), CSSStyleDeclaration.Unit.PX); } }); } } void addElement(Element element) { contentElement.appendChild(element); } void reset() { contentElement.getStyle().setMarginTop(0, CSSStyleDeclaration.Unit.PX); contentElement.setInnerHTML(""); } void setWidth(int width) { scrollableElement.getStyle().setWidth(width, CSSStyleDeclaration.Unit.PX); } public int getWidth() { return scrollableElement.getClientWidth(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/search/SearchMatchRenderer.java
client/src/main/java/com/google/collide/client/editor/search/SearchMatchRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.search; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.util.JsonCollections; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; /** * Search match highlighting. * */ public class SearchMatchRenderer implements LineRenderer { public interface Css extends CssResource { String match(); } public interface Resources extends ClientBundle { @Source("SearchMatchRenderer.css") Css searchMatchRendererCss(); } private final SearchModel model; private boolean inMatch = false; private final JsonArray<Integer> edges; private final Css css; public SearchMatchRenderer(Resources resource, SearchModel model) { this.model = model; edges = JsonCollections.createArray(); css = resource.searchMatchRendererCss(); } @Override public void renderNextChunk(Target target) { int end = edges.get(1); int start = edges.remove(0); /* * TODO: This is caused by back to back matches (which we want to * render separately since we can highlight a single match), maybe a better * way to fix this in the future? */ if (start == end) { end = edges.get(1); start = edges.remove(0); inMatch = !inMatch; } target.render(end - start, inMatch ? css.match() : null); inMatch = !inMatch; } @Override public boolean resetToBeginningOfLine(Line line, int lineNumber) { assert model.getQuery() != null; assert model.getSearchPattern() != null; edges.clear(); String text = line.getText(); RegExp regex = model.getSearchPattern(); /* * We must not forget to clear the lastIndex since it is a global regex, if * we don't it can lead to a false negative for matches. */ regex.setLastIndex(0); MatchResult match = regex.exec(text); if (match == null || match.getGroup(0).isEmpty()) { return false; } do { int start = regex.getLastIndex() - match.getGroup(0).length(); edges.add(start); edges.add(regex.getLastIndex()); match = regex.exec(text); } while (match != null && !match.getGroup(0).isEmpty()); // Handles the edge cases of matching at beginning or end of a line inMatch = true; if (edges.get(0) != 0) { inMatch = false; edges.splice(0, 0, 0); } if (edges.peek() != text.length()) { edges.add(text.length()); } return true; } @Override public boolean shouldLastChunkFillToRight() { return false; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/editor/search/SearchModel.java
client/src/main/java/com/google/collide/client/editor/search/SearchModel.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.editor.search; import com.google.collide.client.editor.EditorContext; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.BasicIncrementalScheduler; import com.google.collide.client.util.ClientStringUtils; import com.google.collide.client.util.IncrementalScheduler; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.DocumentMutator; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.LineInfo; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.RegExpUtils; import com.google.gwt.regexp.shared.RegExp; /** * External handle to search functions in the editor. * * TODO: Handle number of matches changing due to document mutations. * */ public class SearchModel { public static SearchModel create(EditorContext<?> context, Document document, Renderer renderer, ViewportModel viewport, SelectionModel selectionModel, DocumentMutator editorDocumentMutator) { /* * This is a pretty fast operation so by default we guess about 5000 lines * in 100 ms. */ IncrementalScheduler scheduler = new BasicIncrementalScheduler(context.getUserActivityManager(), 100, 5000); SearchTask searchTask = new SearchTask(document, viewport, scheduler); IncrementalScheduler matchScheduler = new BasicIncrementalScheduler(context.getUserActivityManager(), 100, 5000); SearchTask matchTask = new SearchTask(document, viewport, matchScheduler); return new SearchModel(context, document, renderer, viewport, new SearchMatchManager(document, selectionModel, editorDocumentMutator, matchTask), searchTask, selectionModel); } public static SearchModel createWithManagerAndScheduler(EditorContext<?> context, Document document, Renderer renderer, ViewportModel viewport, SearchMatchManager matchManager, IncrementalScheduler scheduler, SelectionModel selectionModel) { return new SearchModel(context, document, renderer, viewport, matchManager, new SearchTask(document, viewport, scheduler), selectionModel); } public interface SearchProgressListener { public void onSearchBegin(); public void onSearchProgress(); public void onSearchDone(); } public interface MatchCountListener { public void onMatchCountChanged(int total); } private class SearchTaskHandler implements SearchTask.SearchTaskExecutor { private RegExp oldSearchPattern; public void setOldSearchPattern(RegExp oldSearchPattern) { this.oldSearchPattern = oldSearchPattern; } @Override public boolean onSearchLine(Line line, int number, boolean shouldRenderLine) { int matches = RegExpUtils.resetAndGetNumberOfMatches(searchPattern, line.getText()); matchManager.addMatches(new LineInfo(line, number), matches); if (shouldRenderLine) { handleViewportLine(line, matches); } return true; } private void handleViewportLine(Line line, int matches) { if (matches > 0) { renderer.requestRenderLine(line); } else if (oldSearchPattern != null && RegExpUtils.resetAndTest(oldSearchPattern, line.getText())) { renderer.requestRenderLine(line); } } } private final SearchMatchRenderer lineRenderer; private String query; private final Renderer renderer; private RegExp searchPattern; private final SearchMatchManager matchManager; private final ViewportModel viewport; private final SearchTask searchTask; private final SelectionModel selectionModel; private final SearchTaskHandler searchTaskHandler; protected SearchModel(EditorContext<?> context, Document document, Renderer renderer, ViewportModel viewport, SearchMatchManager matchManager, SearchTask searchTask, SelectionModel selectionModel) { this.lineRenderer = new SearchMatchRenderer(context.getResources(), this); this.matchManager = matchManager; this.query = ""; this.renderer = renderer; this.viewport = viewport; this.searchTask = searchTask; this.selectionModel = selectionModel; searchTaskHandler = new SearchTaskHandler(); } /** * @return currently active query */ public String getQuery() { return query; } /** * @return currently active search pattern */ public RegExp getSearchPattern() { return searchPattern; } /** * Matches a wildcard type search query in the editor */ public void setQuery(String query) { setQuery(query, null); } /** * Matches a wildcard type search query in the editor * * @param progressListener optional search progress listener. */ public void setQuery(final String query, SearchProgressListener progressListener) { if (query == null) { throw new IllegalArgumentException("Query cannot be null"); } this.query = query; if (query.isEmpty()) { if (searchPattern != null) { matchManager.clearMatches(); cleanupAfterQuery(); } return; } if (searchPattern == null) { // moving from no query to an active query; add the line renderer renderer.addLineRenderer(lineRenderer); } /* * Heuristic for case sensitivity: If the string is all lower-case we match * case-insensitively; otherwise the pattern is case sensitive. */ String regExpOptions = ClientStringUtils.containsUppercase(query) ? "g" : "gi"; // Create the new search pattern searchTaskHandler.setOldSearchPattern(searchPattern); searchPattern = RegExpUtils.createRegExpForWildcardPattern(query, regExpOptions); // setSearchPattern automatically clears any match data matchManager.setSearchPattern(searchPattern); Line line = selectionModel.getCursorLine(); int lineNumber = selectionModel.getCursorLineNumber(); searchTask.searchDocument(searchTaskHandler, progressListener, new LineInfo(line, lineNumber)); } public SearchMatchManager getMatchManager() { return matchManager; } public ListenerRegistrar<MatchCountListener> getMatchCountChangedListenerRegistrar() { return matchManager.getMatchCountChangedListenerRegistrar(); } public void teardown() { searchTask.teardown(); } /** * Cleans up the viewport when we no longer have a query. Rerenders lines that * the last searchPattern has highlighted. */ private void cleanupAfterQuery() { renderer.removeLineRenderer(lineRenderer); LineInfo lineInfo = viewport.getTopLineInfo(); do { if (RegExpUtils.resetAndTest(searchPattern, lineInfo.line().getText())) { renderer.requestRenderLine(lineInfo.line()); } } while (lineInfo.line() != viewport.getBottomLine() && lineInfo.moveToNext()); searchPattern = null; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false