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/NavigatorAreaResizeController.java
client/src/main/java/com/google/collide/client/code/NavigatorAreaResizeController.java
package com.google.collide.client.code; import com.google.collide.client.history.Place; import com.google.collide.client.util.AnimationUtils; import com.google.collide.client.util.ResizeController; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * Class responsible for managing resizing of the Navigation Section. */ class NavigatorAreaResizeController extends ResizeController implements NavigationAreaExpansionEvent.Handler { private static final double DURATION = 0.2; int oldNavWidth; int oldSplitterLeft; private final Element splitter; private final Element navigatorArea; private final Element contentArea; private final int splitterWidth; private final int splitterOverlap; private final Place currentPlace; public NavigatorAreaResizeController(Place currentPlace, CodePerspective.Resources resources, Element splitter, Element navigatorArea, Element contentArea, int splitterWidth, int splitterOverlap) { super(resources, splitter, new ElementInfo(navigatorArea, ResizeProperty.WIDTH), new ElementInfo(splitter, ResizeProperty.LEFT), new ElementInfo(contentArea, ResizeProperty.LEFT)); this.currentPlace = currentPlace; this.splitter = splitter; this.navigatorArea = navigatorArea; this.contentArea = contentArea; this.splitterWidth = splitterWidth; this.splitterOverlap = splitterOverlap; } @Override public void onNavAreaExpansion(NavigationAreaExpansionEvent evt) { int targetNavWidth = oldNavWidth; int targetSplitterLeft = oldSplitterLeft; int targetContentAreaLeft = oldSplitterLeft + splitterWidth; // If we are asked to collapse. if (!evt.shouldExpand()) { // Remember the old sizes if we happen to be expanded. if (!isCollapsed(splitter)) { oldNavWidth = navigatorArea.getClientWidth(); oldSplitterLeft = splitter.getOffsetLeft(); } // We want to collapse. targetNavWidth = 0; targetSplitterLeft = 0; targetContentAreaLeft = 0; } // If we ask to expand, but we are already expanded, do nothing. if (evt.shouldExpand() && !isCollapsed(splitter)) { return; } splitter.getStyle().setLeft(targetSplitterLeft, CSSStyleDeclaration.Unit.PX); splitter.getStyle().setDisplay("none"); AnimationUtils.backupOverflow(navigatorArea.getStyle()); AnimationUtils.animatePropertySet(navigatorArea, "width", targetNavWidth + CSSStyleDeclaration.Unit.PX, DURATION, new EventListener() { @Override public void handleEvent(Event evt) { splitter.getStyle().setDisplay(""); AnimationUtils.restoreOverflow(navigatorArea.getStyle()); } }); AnimationUtils.animatePropertySet( contentArea, "left", targetContentAreaLeft + CSSStyleDeclaration.Unit.PX, DURATION); } @Override public void start() { super.start(); attachDblClickListener(); currentPlace.registerSimpleEventHandler(NavigationAreaExpansionEvent.TYPE, this); } @Override protected void resizeStarted() { // Make sure the content area is to the right of the splitter in the // case where we drag after collapsing. String contentAreaOffset = (splitterOverlap + getSplitter().getOffsetLeft()) + CSSStyleDeclaration.Unit.PX; contentArea.getStyle().setLeft(contentAreaOffset); super.resizeStarted(); } private void attachDblClickListener() { // Double clicking animates the splitter to hide and show the nav area. // Equivalent to an automated resize. splitter.setOndblclick(new EventListener() { @Override public void handleEvent(Event evt) { // We just want to toggle. If it is collapsed, we want to expand. currentPlace.fireEvent(new NavigationAreaExpansionEvent(isCollapsed(splitter))); } }); } private boolean isCollapsed(Element splitter) { return splitter.getOffsetLeft() == 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/code/EditableContentArea.java
client/src/main/java/com/google/collide/client/code/EditableContentArea.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import collide.client.editor.EditorToolbar; import collide.client.filetree.FileTreeUiController; import collide.client.util.Elements; import com.google.collide.client.AppContext; import com.google.collide.client.code.gotodefinition.GoToDefinitionRenderer; import com.google.collide.client.ui.panel.MultiPanel; import com.google.collide.client.ui.panel.PanelContent; import com.google.collide.client.ui.panel.PanelModel; import com.google.collide.client.ui.panel.PanelModel.Builder; import com.google.collide.mvp.ShowableUiComponent; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; import elemental.html.DivElement; /** * The main content area on the CodePerspective. * */ public class EditableContentArea extends MultiPanel<PanelModel, EditableContentArea.View> { /** * Static factory method for obtaining an instance of the EditableContentArea. */ public static EditableContentArea create( View view, AppContext appContext, EditorBundle editorBundle, FileTreeUiController controller) { final EditorToolbar toolBar = DefaultEditorToolBar.create( view.getEditorToolBarView(), FileSelectedPlace.PLACE, appContext, editorBundle); // Hook presenter in the editor bundle to the view in the header editorBundle.getBreadcrumbs().setView(view.getBreadcrumbsView()); return new EditableContentArea(view, toolBar, controller); } /** * Style names. */ public interface Css extends CssResource { String base(); String contentHeader(); String contentContainer(); int editableContentAreaRight(); } public interface Resources extends GoToDefinitionRenderer.Resources, DefaultEditorToolBar.Resources, WorkspaceLocationBreadcrumbs.Resources, NoFileSelectedPanel.Resources, UneditableDisplay.Resources { @Source({"collide/client/common/constants.css", "EditableContentArea.css"}) Css editableContentAreaCss(); } /** * The View for the EditableContentArea. */ public static class View extends MultiPanel.View<PanelModel> { private DivElement header; private DivElement content; private final WorkspaceLocationBreadcrumbs.View breadcrumbsView; private final DefaultEditorToolBar.View editorToolBarView; private final Css css; public View(Resources res, boolean detached) { super(Elements.createDivElement(res.editableContentAreaCss().base()), detached); this.css = res.editableContentAreaCss(); // Instantiate sub-views. this.breadcrumbsView = new WorkspaceLocationBreadcrumbs.View(res); this.editorToolBarView = new DefaultEditorToolBar.View(res, detached); createDom(); } @Override public Element getContentElement() { return content; } @Override public Element getHeaderElement() { return header; } public DefaultEditorToolBar.View getEditorToolBarView() { return editorToolBarView; } public WorkspaceLocationBreadcrumbs.View getBreadcrumbsView() { return breadcrumbsView; } public int getDefaultEditableContentAreaRight() { return css.editableContentAreaRight(); } private void createDom() { Element elem = getElement(); header = Elements.createDivElement(css.contentHeader()); content = Elements.createDivElement(css.contentContainer()); elem.appendChild(header); elem.appendChild(content); header.appendChild(breadcrumbsView.getElement()); header.appendChild(editorToolBarView.getElement()); } } private final EditorToolbar toolBar; private FileTreeUiController fileController; @Override public void clearNavigator() { fileController.clearSelectedNodes(); } @Override public void setContent(PanelContent panelContent, PanelModel settings) { // TODO consider deleting this superfluous override? if (panelContent instanceof FileContent) { super.setContent(panelContent, settings); }else { //use an inner multipanel to add, instead of replace, content panels. super.setContent(panelContent, settings); } }; public EditableContentArea(View view, EditorToolbar toolBar, FileTreeUiController controller) { super(view); this.toolBar = toolBar; this.fileController = controller; } @Override public ShowableUiComponent<?> getToolBar() { return getEditorToolBar().asComponent(); } public EditorToolbar getEditorToolBar() { return toolBar; } @Override public Builder<PanelModel> newBuilder() { return defaultBuilder(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/UneditableDisplay.java
client/src/main/java/com/google/collide/client/code/UneditableDisplay.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import collide.client.util.Elements; import com.google.collide.client.util.PathUtil; import com.google.collide.dto.FileContents; import com.google.collide.dto.FileContents.ContentType; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; import elemental.html.ImageElement; /** * A display widget for uneditable things. */ public class UneditableDisplay extends UiComponent<UneditableDisplay.View> implements FileContent { public static UneditableDisplay create(View view) { return new UneditableDisplay(view); } public interface Css extends CssResource { String top(); String image(); } public interface Resources extends ClientBundle { @Source("UneditableDisplay.css") Css uneditableDisplayCss(); } public static class View extends CompositeView<Void> { private final Resources res; public View(Resources res) { super(Elements.createDivElement(res.uneditableDisplayCss().top())); this.res = res; } } private UneditableDisplay(View view) { super(view); } @Override public PathUtil filePath() { return null; } public void displayUneditableFileContents(FileContents uneditableFile) { getView().getElement().setInnerHTML(""); if (uneditableFile.getContentType() == ContentType.IMAGE) { ImageElement image = Elements.createImageElement(getView().res.uneditableDisplayCss().image()); image.setSrc("data:" + uneditableFile.getMimeType() + ";base64," + uneditableFile.getContents()); getView().getElement().appendChild(image); } else { getView().getElement().setTextContent("This file cannot be edited or displayed."); } } @Override public Element getContentElement() { return getView().getElement(); } @Override public void onContentDisplayed() { } @Override public void onContentDestroyed() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/PluginContent.java
client/src/main/java/com/google/collide/client/code/PluginContent.java
package com.google.collide.client.code; import com.google.collide.client.ui.panel.PanelContent; import com.google.collide.client.util.ResizeBounds.BoundsBuilder; public interface PluginContent extends PanelContent{ /** * @return The string key used to identify a given plugin; * this value should be human readable, and machine friendly. * * It will be used as header-groups for content panels */ String getNamespace(); BoundsBuilder getBounds(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/SnapshotRequestedEvent.java
client/src/main/java/com/google/collide/client/code/SnapshotRequestedEvent.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * An event which can be fired to indicate that a snapshot is requested and the * dialog should be opened if possible. */ public class SnapshotRequestedEvent extends GwtEvent<SnapshotRequestedEvent.Handler> { /** * Handler interface for getting notified when the right sidebar is expanded * or collapsed. */ public interface Handler extends EventHandler { void onSnapshotRequested(SnapshotRequestedEvent evt); } public static final Type<Handler> TYPE = new Type<Handler>(); private final String suggestedLabel; public SnapshotRequestedEvent() { this(null); } public SnapshotRequestedEvent(String suggestedLabel) { this.suggestedLabel = suggestedLabel; } public String getSuggestedLabel() { return suggestedLabel; } @Override protected void dispatch(Handler handler) { handler.onSnapshotRequested(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/code/WorkspaceNavigation.java
client/src/main/java/com/google/collide/client/code/WorkspaceNavigation.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.util.ResizeController; import com.google.collide.client.util.ResizeController.ResizeProperty; import com.google.collide.client.workspace.outline.OutlineSection; 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.resources.client.CssResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; /** * The navigation area for the workspace Shell. */ public class WorkspaceNavigation extends UiComponent<WorkspaceNavigation.View> { /** * Static factory method for obtaining an instance of the WorkspaceNavigation. */ public static WorkspaceNavigation create(View view, WorkspaceNavigationSection<?>[] topSections, WorkspaceNavigationSection<?>[] bottomSections, WorkspaceNavigationToolBar navigationToolBar) { WorkspaceNavigation workspaceNavigation = new WorkspaceNavigation(view, navigationToolBar); for (WorkspaceNavigationSection<?> topSection : topSections) { workspaceNavigation.addTopSection(topSection); } for (WorkspaceNavigationSection<?> bottomSection : bottomSections) { bottomSection.setVisible(false); workspaceNavigation.addBottomSection(bottomSection); } return workspaceNavigation; } /** * Style names for this presenter's view. */ public interface Css extends CssResource { /** * Returns the height of the bottom section. */ String bottomSectionsHeight(); String root(); String topSections(); String bottomSections(); String bottomSectionsClosed(); String bottomSectionsAnimator(); String bottomSectionsContent(); String splitter(); } /** * CSS and images used by this presenter. */ interface Resources extends FileTreeSection.Resources, CollaborationSection.Resources, OutlineSection.Resources, WorkspaceNavigationToolBar.Resources, ResizeController.Resources { @Source({"collide/client/common/constants.css", "WorkspaceNavigation.css"}) Css workspaceNavigationCss(); } /** * View for this presenter that happens to be a simple overlay type. */ public static class View extends CompositeView<Void> { @UiTemplate("WorkspaceNavigation.ui.xml") interface MyBinder extends UiBinder<com.google.gwt.dom.client.DivElement, View> { } private static MyBinder binder = GWT.create(MyBinder.class); @UiField(provided = true) final Css css; @UiField DivElement topSections; @UiField DivElement splitter; @UiField DivElement bottomSections; @UiField DivElement bottomSectionsAnimator; @UiField DivElement bottomSectionsContent; @UiField DivElement toolbarHolder; WorkspaceNavigationToolBar.View navigationToolBarView; protected View(Resources res) { this.css = res.workspaceNavigationCss(); this.navigationToolBarView = new WorkspaceNavigationToolBar.View(res); setElement(Elements.asJsElement(binder.createAndBindUi(this))); setBottomSectionsVisible(false); Elements.asJsElement(toolbarHolder).appendChild(navigationToolBarView.getElement()); /* * Add a resize controller. We set the default value programatically * because we use padding, which skews the height calculations in * ResizeController. */ // TODO: Move this to the presenter. ResizeController splitterController = new ResizeController(res, Elements.asJsElement(splitter), new ResizeController.ElementInfo(Elements.asJsElement(bottomSections), ResizeProperty.HEIGHT, css.bottomSectionsHeight()), new ResizeController.ElementInfo(Elements.asJsElement(bottomSectionsAnimator), ResizeProperty.HEIGHT, css.bottomSectionsHeight()), new ResizeController.ElementInfo(Elements.asJsElement(bottomSectionsContent), ResizeProperty.HEIGHT, css.bottomSectionsHeight())); splitterController.setNegativeDeltaH(true); splitterController.start(); } public WorkspaceNavigationToolBar.View getNavigationToolBarView() { return navigationToolBarView; } private void setBottomSectionsVisible(boolean isVisible) { // Use a CSS class to set the height to 0px so we don't override the // height attribute set by the resize controller. CssUtils.setClassNameEnabled(Elements.asJsElement(bottomSections), css.bottomSectionsClosed(), !isVisible); CssUtils.setClassNameEnabled(Elements.asJsElement(bottomSectionsAnimator), css.bottomSectionsClosed(), !isVisible); CssUtils.setDisplayVisibility2(Elements.asJsElement(splitter), isVisible); } } /** * The bottom section that is currently visible. */ private WorkspaceNavigationSection<?> shownBottomSection; /** * The bottom section that was previously visible, and may need to be hidden * when a new section is shown. We don't hide the old section while it is * animating out of view, so we need to keep track of it even if it isn't * logically selected. */ private WorkspaceNavigationSection<?> previouslyShownBottomSection; private final WorkspaceNavigationToolBar navigationToolBar; WorkspaceNavigation(View view, WorkspaceNavigationToolBar navigationToolBar) { super(view); this.navigationToolBar = navigationToolBar; // Hide the bottom sections by default. showBottomSection(null); } /** * Takes in a {@link WorkspaceNavigationSection} and adds it to the top * sections. * * @param section section to add */ void addTopSection(WorkspaceNavigationSection<?> section) { Elements.asJsElement(getView().topSections).appendChild(section.getView().getElement()); } /** * Takes in a {@link WorkspaceNavigationSection} and adds it to the bottom * sections. * * @param section section to add */ void addBottomSection(WorkspaceNavigationSection<?> section) { Elements.asJsElement(getView().bottomSectionsContent) .appendChild(section.getView().getElement()); } /** * Hide currently shown navigation section and show the given one. * * @param section section to show, or {@code null} to hide shown section */ void showBottomSection(WorkspaceNavigationSection<?> section) { if (section == shownBottomSection) { return; } /* * Hide the old section, but only if something else if going to be shown. * Otherwise, we want to animate the old section out of view. */ if (previouslyShownBottomSection != null && section != null) { previouslyShownBottomSection.setVisible(false); previouslyShownBottomSection = null; } if (section != null) { section.setVisible(true); previouslyShownBottomSection = section; } getView().setBottomSectionsVisible(section != null); shownBottomSection = section; } /** * Shows the specified section if it is not visible, or hides the section if * it is visible. * * @return true if the section is now showing, false if not */ boolean toggleBottomSection(WorkspaceNavigationSection<?> section) { if (section == shownBottomSection) { showBottomSection(null); return false; } else { showBottomSection(section); return true; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/RightSidebarResizeController.java
client/src/main/java/com/google/collide/client/code/RightSidebarResizeController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import com.google.collide.client.history.Place; import com.google.collide.client.util.AnimationUtils; import com.google.collide.client.util.ResizeController; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * Class responsible for managing resizing of the right sidebar. * */ class RightSidebarResizeController extends ResizeController implements RightSidebarExpansionEvent.Handler, RightSidebarToggleEvent.Handler { private static enum ExpansionState { COLLAPSED, EXPANDED, COLLAPSING, EXPANDING } private static final double DURATION = 0.2; private static final int DEFAULT_SIDEBAR_WIDTH = 300; private final int collapsedSplitterRight; private final int defaultEditableContentAreaRight; private final Element splitter; private final Element sidebarArea; private final Element contentArea; private final int splitterWidth; private final Place currentPlace; int oldSidebarWidth; int oldSplitterRight; ExpansionState expansionState = ExpansionState.COLLAPSED; public RightSidebarResizeController(Place currentPlace, CodePerspective.Resources resources, Element splitter, Element sidebarArea, Element contentArea, int splitterWidth, int collapsedSplitterRight, int defaultEditableContentAreaRight) { super(resources, splitter, new ElementInfo(sidebarArea, ResizeProperty.WIDTH), new ElementInfo( splitter, ResizeProperty.RIGHT), new ElementInfo(contentArea, ResizeProperty.RIGHT)); this.currentPlace = currentPlace; this.splitter = splitter; this.sidebarArea = sidebarArea; this.contentArea = contentArea; this.splitterWidth = splitterWidth; this.defaultEditableContentAreaRight = defaultEditableContentAreaRight; oldSplitterRight = this.collapsedSplitterRight = collapsedSplitterRight; } @Override public void onRightSidebarExpansion(RightSidebarExpansionEvent evt) { showSidebar(evt.shouldExpand()); } private void showSidebar(boolean show) { int targetSidebarWidth = oldSidebarWidth; int targetSplitterRight = oldSplitterRight; int targetContentAreaRight = oldSplitterRight + splitterWidth; if (show) { // If we ask to expand, but we are already expanded, do nothing. if (!isAnimating() && !isCollapsed()) { return; } if (targetSidebarWidth <= 0) { targetSidebarWidth = DEFAULT_SIDEBAR_WIDTH; targetSplitterRight = targetSidebarWidth - splitterWidth; targetContentAreaRight = targetSidebarWidth; } } else { // Remember the old sizes if we happen to be expanded. if (!isAnimating() && !isCollapsed()) { oldSidebarWidth = sidebarArea.getClientWidth(); oldSplitterRight = getSplitterOffsetRight(); } // We want to collapse. targetSidebarWidth = splitterWidth; targetSplitterRight = collapsedSplitterRight; targetContentAreaRight = defaultEditableContentAreaRight; } splitter.getStyle().setRight(targetSplitterRight, CSSStyleDeclaration.Unit.PX); splitter.getStyle().setDisplay("none"); final String targetSidebarVisibility = targetSplitterRight <= 0 ? CSSStyleDeclaration.Visibility.HIDDEN : ""; AnimationUtils.backupOverflow(sidebarArea.getStyle()); AnimationUtils.animatePropertySet(sidebarArea, "width", targetSidebarWidth + CSSStyleDeclaration.Unit.PX, DURATION, new EventListener() { @Override public void handleEvent(Event evt) { splitter.getStyle().setDisplay(""); AnimationUtils.restoreOverflow(sidebarArea.getStyle()); sidebarArea.getStyle().setVisibility(targetSidebarVisibility); expansionState = expansionState == ExpansionState.EXPANDING ? ExpansionState.EXPANDED: ExpansionState.COLLAPSED; } }); AnimationUtils.animatePropertySet( contentArea, "right", targetContentAreaRight + CSSStyleDeclaration.Unit.PX, DURATION); sidebarArea.getStyle().setVisibility(""); expansionState = show ? ExpansionState.EXPANDING : ExpansionState.COLLAPSING; } @Override public void onRightSidebarToggled(RightSidebarToggleEvent evt) { showSidebar(isCollapsed()); } @Override public void start() { super.start(); attachDblClickListener(); currentPlace.registerSimpleEventHandler(RightSidebarExpansionEvent.TYPE, this); currentPlace.registerSimpleEventHandler(RightSidebarToggleEvent.TYPE, this); } @Override protected void resizeStarted() { sidebarArea.getStyle().setVisibility(""); super.resizeStarted(); } private void attachDblClickListener() { // Double clicking animates the splitter to hide and show the nav area. // Equivalent to an automated resize. splitter.setOndblclick(new EventListener() { @Override public void handleEvent(Event evt) { // We just want to toggle. If it is collapsed, we want to expand. currentPlace.fireEvent(new RightSidebarExpansionEvent(isCollapsed())); } }); } private boolean isAnimating() { return expansionState == ExpansionState.EXPANDING || expansionState == ExpansionState.COLLAPSING; } private boolean isCollapsed() { if (isAnimating()) { // Splitter is hidden at this point. return expansionState == ExpansionState.COLLAPSING; } return getSplitterOffsetRight() == collapsedSplitterRight; } private int getSplitterOffsetRight() { return splitter.getOffsetParent().getClientWidth() - splitter.getOffsetLeft() - splitter.getOffsetWidth(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/WorkspaceNavigationToolBar.java
client/src/main/java/com/google/collide/client/code/WorkspaceNavigationToolBar.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import collide.client.common.CommonResources; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.ui.menu.PositionController; import com.google.collide.client.ui.tooltip.Tooltip; import com.google.collide.client.workspace.outline.OutlineSection; 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.Node; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * Footer toolbar in the WorkspaceNavigation on the left of the CodePerspective below the file tree. */ public class WorkspaceNavigationToolBar extends UiComponent<WorkspaceNavigationToolBar.View> { /** * Creates the default version of the footer toolbar in the WorkspaceNavigation. */ public static WorkspaceNavigationToolBar create( View view, CollaborationSection collabSection, OutlineSection outlineSection) { return new WorkspaceNavigationToolBar(view, collabSection, outlineSection); } /** * Style names associated with elements in the toolbar. */ public interface Css extends CssResource { String outerBorder(); String toolBar(); String collaborateIcon(); String deltaIcon(); String navigatorIcon(); } /** * Images and CssResources consumed by the WorkspaceNavigationToolBar. */ public interface Resources extends Tooltip.Resources, CommonResources.BaseResources { @Source("collaborate_icon.png") ImageResource collaborateIcon(); /** * Returns the image used for the workspace delta icon. * * The method deltaIcon is taken by * {@link com.google.collide.client.diff.DiffCommon.Resources#deltaIcon()}. */ @Source("delta_icon.png") ImageResource workspaceDeltaIcon(); @Source("navigator_icon.png") ImageResource navigatorIcon(); @Source({"WorkspaceNavigationToolBar.css", "constants.css", "collide/client/common/constants.css"}) Css workspaceNavigationToolBarCss(); } /** * The View for the WorkspaceNavigationToolBar. */ public static class View extends CompositeView<ViewEvents> { @UiTemplate("WorkspaceNavigationToolBar.ui.xml") interface MyBinder extends UiBinder<DivElement, View> { } static MyBinder binder = GWT.create(MyBinder.class); @UiField DivElement toolBar; @UiField DivElement collaborateButton; @UiField DivElement collaborateIcon; @UiField DivElement deltaButton; @UiField DivElement deltaIcon; @UiField DivElement navigatorButton; @UiField DivElement navigatorIcon; @UiField(provided = true) final Resources res; private Element activeButton; public View(Resources res) { this.res = res; setElement(Elements.asJsElement(binder.createAndBindUi(this))); attachHandlers(); // Tooltips Tooltip.create(res, Elements.asJsElement(collaborateButton), PositionController.VerticalAlign.TOP, PositionController.HorizontalAlign.MIDDLE, "Work with collaborators"); Tooltip.create(res, Elements.asJsElement(deltaButton), PositionController.VerticalAlign.TOP, PositionController.HorizontalAlign.MIDDLE, "See what's changed in this branch"); Tooltip.create(res, Elements.asJsElement(navigatorButton), PositionController.VerticalAlign.TOP, PositionController.HorizontalAlign.MIDDLE, "View the code navigator"); } protected void attachHandlers() { getElement().setOnclick(new EventListener() { @Override public void handleEvent(Event evt) { ViewEvents delegate = getDelegate(); if (delegate == null) { return; } Node target = (Node) evt.getTarget(); if (collaborateButton.isOrHasChild(target)) { delegate.onCollaborateButtonClicked(); } else if (deltaButton.isOrHasChild(target)) { delegate.onDeltaButtonClicked(); } else if (navigatorButton.isOrHasChild(target)) { delegate.onNavigatorButtonClicked(); } } }); } private void setActiveButton(Element button) { if (this.activeButton != null) { this.activeButton.removeClassName(res.baseCss().drawerIconButtonActiveLight()); } this.activeButton = button; if (button != null) { button.addClassName(res.baseCss().drawerIconButtonActiveLight()); } } } /** * Events reported by the DefaultEditorToolBar's View. */ interface ViewEvents { void onCollaborateButtonClicked(); void onDeltaButtonClicked(); void onNavigatorButtonClicked(); } private class ToolbarViewEvents implements WorkspaceNavigationToolBar.ViewEvents { @Override public void onCollaborateButtonClicked() { toggleSection(collabSection, Elements.asJsElement(getView().collaborateButton)); } @Override public void onDeltaButtonClicked() { // used to show delta section } @Override public void onNavigatorButtonClicked() { toggleSection(outlineSection, Elements.asJsElement(getView().navigatorButton)); } } private final OutlineSection outlineSection; private final CollaborationSection collabSection; private WorkspaceNavigation navigation; WorkspaceNavigationToolBar( View view, CollaborationSection collabSection, OutlineSection outlineSection) { super(view); this.collabSection = collabSection; this.outlineSection = outlineSection; getView().setDelegate(new ToolbarViewEvents()); } public void setWorkspaceNavigation(WorkspaceNavigation navigation) { this.navigation = navigation; } void hideDeltaButton() { CssUtils.setDisplayVisibility2((Element) (getView().deltaButton), false); } private boolean toggleSection(WorkspaceNavigationSection<?> section, Element button) { if (navigation == null) { return false; } boolean showing = navigation.toggleBottomSection(section); if (showing) { getView().setActiveButton(button); } else { getView().setActiveButton(null); } return showing; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/FileTreeSection.java
client/src/main/java/com/google/collide/client/code/FileTreeSection.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import collide.client.common.CanRunApplication; import collide.client.filetree.FileTreeController; import collide.client.filetree.FileTreeModel; import collide.client.filetree.FileTreeNode; import collide.client.filetree.FileTreeNodeDataAdapter; import collide.client.filetree.FileTreeNodeRenderer; import collide.client.filetree.FileTreeUiController; import collide.client.treeview.Tree; import collide.client.util.Elements; import com.google.collide.client.history.Place; import com.google.collide.client.ui.tooltip.Tooltip; import com.google.collide.dto.DirInfo; import com.google.collide.dto.ProjectInfo; import com.google.gwt.resources.client.CssResource; import elemental.dom.Element; /** * {@link WorkspaceNavigationSection} that is the presenter for the File Tree. * * This class owns the instances of the {@link FileTreeUiController}, and the {@link Tree} widget. * */ public class FileTreeSection extends WorkspaceNavigationSection<FileTreeSection.View> { /** * Static factory method for obtaining an instance of the FileTreeSection. */ public static FileTreeSection create(Place place, FileTreeController<?> controller, FileTreeModel fileTreeModel, CanRunApplication applicationRunner) { // create the view FileTreeSection.View view = new FileTreeSection.View(controller.getResources()); // Create the Tree presenter. FileTreeNodeRenderer nodeRenderer = FileTreeNodeRenderer.create(controller.getResources()); FileTreeNodeDataAdapter nodeDataAdapter = new FileTreeNodeDataAdapter(); Tree<FileTreeNode> tree = Tree.create( view.treeView, nodeDataAdapter, nodeRenderer, controller.getResources()); // Create the UI controller. FileTreeUiController treeUiController = FileTreeUiController.create(place, fileTreeModel, tree, controller, applicationRunner); // attach a file tree menu to the button treeUiController.getContextMenuController() .createMenuDropdown(Elements.asJsElement(view.menuButton)); // Instantiate and return the FileTreeSection. FileTreeSection fileTreeSection = new FileTreeSection(view, tree, treeUiController, fileTreeModel); return fileTreeSection; } public interface Css extends CssResource { String root(); } /** * CSS and images used by the FileTreeSection. */ public interface Resources extends WorkspaceNavigationSection.Resources, Tooltip.Resources, FileTreeNodeRenderer.Resources { @Source("FileTreeSection.css") Css workspaceNavigationFileTreeSectionCss(); } /** * View for the FileTreeSection. */ public static class View extends WorkspaceNavigationSection.View<WorkspaceNavigationSection.ViewEvents> { final Element root; Tree.View<FileTreeNode> treeView; View(Resources res) { super(res); // Instantiate subviews. this.treeView = new Tree.View<FileTreeNode>(res); root = Elements.createDivElement(res.workspaceNavigationFileTreeSectionCss().root()); root.appendChild(treeView.getElement()); // Initialize the View. setTitle("Project Files"); setStretch(true); setShowMenuButton(true); setContent(root); setContentAreaScrollable(true); setUnderlineHeader(true); title.addClassName(css.headerLink()); } } private class ViewEventsImpl extends WorkspaceNavigationSection.AbstractViewEventsImpl { @Override public void onTitleClicked() { if (projectInfo != null) { // was goto landing } } } private final Tree<FileTreeNode> tree; private final FileTreeUiController fileTreeUiController; private ProjectInfo projectInfo; private final FileTreeModel fileTreeModel; private final boolean isReadOnly = false; private final FileTreeModel.TreeModelChangeListener fileTreeModelChangeListener = new FileTreeModel.BasicTreeModelChangeListener() { @Override public void onTreeModelChange() { updateProjectTemplatePickerVisibility(); } }; FileTreeSection(View view, Tree<FileTreeNode> tree, FileTreeUiController fileTreeUiController, FileTreeModel fileTreeModel) { super(view); view.setDelegate(new ViewEventsImpl()); this.tree = tree; this.fileTreeUiController = fileTreeUiController; this.fileTreeModel = fileTreeModel; fileTreeModel.addModelChangeListener(fileTreeModelChangeListener); getView().setTitle("Collide Source"); updateProjectTemplatePickerVisibility(); } public void cleanup() { fileTreeModel.removeModelChangeListener(fileTreeModelChangeListener); } public Tree<FileTreeNode> getTree() { return tree; } public FileTreeUiController getFileTreeUiController() { return fileTreeUiController; } private void updateProjectTemplatePickerVisibility() { if (isReadOnly) { return; } DirInfo root = (DirInfo) fileTreeModel.getWorkspaceRoot(); /* * If it is null, the file tree hasn't been loaded yet so we can't be sure whether or not there * are files, don't show it yet */ boolean showPicker = root != null && root.getFiles().isEmpty() && root.getSubDirectories().isEmpty(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/CodePerspective.java
client/src/main/java/com/google/collide/client/code/CodePerspective.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.AppContext; import com.google.collide.client.code.autocomplete.integration.AutocompleteUiController; import com.google.collide.client.code.debugging.DebuggingModelRenderer; import com.google.collide.client.code.debugging.DebuggingSidebar; import com.google.collide.client.code.debugging.EvaluationPopupController; import com.google.collide.client.code.parenmatch.ParenMatchHighlighter; import com.google.collide.client.diff.DeltaInfoBar; import com.google.collide.client.diff.EditorDiffContainer; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.renderer.LineNumberRenderer; import com.google.collide.client.filehistory.FileHistory; import com.google.collide.client.filehistory.TimelineNode; import com.google.collide.client.history.Place; import com.google.collide.client.syntaxhighlighter.SyntaxHighlighterRenderer; import com.google.collide.client.util.ResizeController; import com.google.collide.client.workspace.Header; import com.google.collide.codemirror2.CodeMirror2; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; import com.google.gwt.resources.client.CssResource; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.html.DivElement; // TODO: Rename the editor package to the code package since it should // encapsulate the CodePerspective. Then move code editor code to editor.core etc... /** * Presenter for the code perspective. * * Contains: * * 1. Project navigation tree for current workspace. * * 2. Our working content area (where will attach the editor). * * 3. Right sidebar (where will attach debugging state panel). * * 4. PanelContent area header (where will be shown path to the file, and other * controls). * */ public class CodePerspective extends UiComponent<CodePerspective.View> { /** * Static factory method for obtaining an instance of the CodePerspective. */ public static CodePerspective create(View view, Place currentPlace, WorkspaceNavigation nav, EditableContentArea contentArea, AppContext context, boolean detached) { CodePerspective codePerspective = new CodePerspective(view, currentPlace, nav, contentArea, context); codePerspective.initResizeControllers(detached); return codePerspective; } /** * CSS and images used by the CodePerspective. */ public interface Resources extends Header.Resources, FileHistory.Resources, TimelineNode.Resources, WorkspaceNavigation.Resources, EditorDiffContainer.Resources, Editor.Resources, SyntaxHighlighterRenderer.Resources, LineNumberRenderer.Resources, ParenMatchHighlighter.Resources, DebuggingModelRenderer.Resources, DebuggingSidebar.Resources, EvaluationPopupController.Resources, DeltaInfoBar.Resources, CodeMirror2.Resources, EditableContentArea.Resources, AutocompleteUiController.Resources { @Source({"CodePerspective.css", "collide/client/common/constants.css"}) Css codePerspectiveCss(); } /** * Style names. */ public interface Css extends CssResource { String base(); int collapsedRightSplitterRight(); String navArea(); int navWidth(); String resizing(); String splitter(); String rightSplitter(); int splitterWidth(); int splitterOverlap(); String rightSidebarContentContainer(); } /** * The View for the CodePerspective. */ public static class View extends CompositeView<Void> { private final Resources res; private final Css css; private final WorkspaceNavigation.View navView; private final EditableContentArea.View contentView; /** * Wrapper element for the WorkspaceNavigation.View. We need a wrapper * because of the behavior of flex box. */ private DivElement navArea; /** Splitter between the navigator and content area. */ private DivElement splitter; /** Splitter between the content area and right sidebar. */ private DivElement rightSplitter; /** Container for the right sidebar. */ private DivElement rightSidebarContentContainer; public View(Resources res, boolean detached) { this.res = res; this.css = res.codePerspectiveCss(); this.navView = new WorkspaceNavigation.View(res); this.contentView = initView(res, detached); // Create the DOM and connect the elements together. setElement(Elements.createDivElement(css.base())); createDom(); } public EditableContentArea.View initView( Resources res, boolean detached) { return new EditableContentArea.View(res, detached); } public Element getSidebarElement() { return rightSidebarContentContainer; } public Element getNavigationElement() { return navArea; } public WorkspaceNavigation.View getNavigationView() { return navView; } public EditableContentArea.View getContentView() { return contentView; } public Element getSplitter() { return splitter; } public Element getRightSplitter() { return rightSplitter; } public Element getRightSidebarElement() { return rightSidebarContentContainer; } /** * Create the initial DOM structure for the workspace shell. */ private void createDom() { // Instantiate DOM elems. navArea = Elements.createDivElement(css.navArea()); splitter = Elements.createDivElement(css.splitter()); rightSplitter = Elements.createDivElement(css.rightSplitter()); rightSidebarContentContainer = Elements.createDivElement(css.rightSidebarContentContainer()); Element elem = getElement(); navArea.appendChild(navView.getElement()); elem.appendChild(navArea); elem.appendChild(splitter); elem.appendChild(contentView.getElement()); // Attach the right sidebar and splitter to the base element of the // WorkspaceContentArea.View. contentView.getElement().appendChild(rightSplitter); contentView.getElement().appendChild(rightSidebarContentContainer); rightSidebarContentContainer.getStyle().setVisibility(CSSStyleDeclaration.Visibility.HIDDEN); } public Element detach() { contentView.getElement().removeChild(rightSplitter); contentView.getElement().removeChild(rightSidebarContentContainer); getElement().removeChild(contentView.getElement()); getElement().removeChild(splitter); navArea.getStyle().setWidth(100, "%"); contentView.getElement().getStyle().setLeft(0, "px"); contentView.getElement().getStyle().setRight(5, "px"); contentView.getElement().getStyle().setTop(0, "px"); getElement().getStyle().setTop(0, "em"); // contentView.getContentElement().addClassName(""); return contentView.getElement(); } } final WorkspaceNavigation nav; final EditableContentArea contentArea; private ResizeController leftResizeController; private ResizeController rightResizeController; private final Place currentPlace; CodePerspective(View view, Place currentPlace, WorkspaceNavigation nav, EditableContentArea contentArea, AppContext context) { super(view); this.currentPlace = currentPlace; this.nav = nav; this.contentArea = contentArea; } public EditableContentArea getContentArea() { return contentArea; } private void initResizeControllers(boolean detached) { View view = getView(); leftResizeController = new NavigatorAreaResizeController(currentPlace, view.res, view.splitter, view.navArea, view.contentView.getElement(), view.css.splitterWidth(), view.css.splitterOverlap()); leftResizeController.start(); if (detached) { CssUtils.setDisplayVisibility2(view.rightSplitter, false); CssUtils.setDisplayVisibility2(view.rightSidebarContentContainer, false); } rightResizeController = new RightSidebarResizeController(currentPlace, view.res, view.rightSplitter, view.rightSidebarContentContainer, view.contentView.getContentElement(), view.css.splitterWidth(), view.css.collapsedRightSplitterRight(), contentArea.getView().getDefaultEditableContentAreaRight()); rightResizeController.setNegativeDeltaW(true); rightResizeController.start(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/lang/DartLanguageHelper.java
client/src/main/java/com/google/collide/client/code/lang/DartLanguageHelper.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.input.ActionExecutor; 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.gwt.regexp.shared.RegExp; /** * Dart-specific {@link LanguageHelper}. */ public class DartLanguageHelper extends DefaultActionExecutor implements LanguageHelper { private static final RegExp COMMENT_CHECKER = RegExp.compile("^\\s*//"); DartLanguageHelper() { addAction(CommonActions.TOGGLE_COMMENT, new Shortcut() { @Override public boolean event(InputScheme scheme, SignalEvent event) { return toggleComments(scheme.getInputController().getEditor()); } }); } public boolean toggleComments(Editor editor) { editor.getSelection().toggleComments(editor.getEditorDocumentMutator(), COMMENT_CHECKER, "//"); return true; } @Override public ActionExecutor getActionExecutor() { return this; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/lang/NoneLanguageHelper.java
client/src/main/java/com/google/collide/client/code/lang/NoneLanguageHelper.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.input.ActionExecutor; import com.google.collide.client.editor.input.InputScheme; /** * Implementation that do not do anything language specific. * */ class NoneLanguageHelper implements LanguageHelper, ActionExecutor { @Override public boolean execute(String actionName, InputScheme scheme, SignalEvent event) { return false; } @Override public ActionExecutor getActionExecutor() { return this; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/lang/JsLanguageHelper.java
client/src/main/java/com/google/collide/client/code/lang/JsLanguageHelper.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.input.ActionExecutor; 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.gwt.regexp.shared.RegExp; /** * JS-specific implementation {@link LanguageHelper}. */ class JsLanguageHelper extends DefaultActionExecutor implements LanguageHelper { private static final RegExp COMMENT_CHECKER = RegExp.compile("^\\s*//"); JsLanguageHelper() { addAction(CommonActions.TOGGLE_COMMENT, new Shortcut(){ @Override public boolean event(InputScheme scheme, SignalEvent event) { return toggleComments(scheme.getInputController().getEditor()); } }); } public boolean toggleComments(Editor editor) { editor.getSelection().toggleComments(editor.getEditorDocumentMutator(), COMMENT_CHECKER, "//"); return true; } @Override public ActionExecutor getActionExecutor() { return this; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/lang/PyLanguageHelper.java
client/src/main/java/com/google/collide/client/code/lang/PyLanguageHelper.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.input.ActionExecutor; 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.gwt.regexp.shared.RegExp; /** * PY-specific implementation {@link LanguageHelper}. */ class PyLanguageHelper extends DefaultActionExecutor implements LanguageHelper { private static final RegExp COMMENT_CHECKER = RegExp.compile("^\\s*#"); PyLanguageHelper() { addAction(CommonActions.TOGGLE_COMMENT, new Shortcut(){ @Override public boolean event(InputScheme scheme, SignalEvent event) { return toggleComments(scheme.getInputController().getEditor()); } }); } public boolean toggleComments(Editor editor) { editor.getSelection().toggleComments(editor.getEditorDocumentMutator(), COMMENT_CHECKER, "#"); return true; } @Override public ActionExecutor getActionExecutor() { return this; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/lang/LanguageHelper.java
client/src/main/java/com/google/collide/client/code/lang/LanguageHelper.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang; import com.google.collide.client.editor.input.ActionExecutor; /** * Interface that provides language-specific information / methods. */ public interface LanguageHelper { ActionExecutor getActionExecutor(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/lang/LanguageHelperResolver.java
client/src/main/java/com/google/collide/client/code/lang/LanguageHelperResolver.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.lang; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Object thad holds instances of {@link LanguageHelper} and returns * corresponding instance by given {@link SyntaxType}. */ public class LanguageHelperResolver { private static LanguageHelperResolver instance; private final JsonStringMap<LanguageHelper> mapping; private LanguageHelperResolver() { mapping = JsonCollections.createMap(); mapping.put(SyntaxType.CSS.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.CPP.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.DART.getName(), new DartLanguageHelper()); mapping.put(SyntaxType.GO.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.HTML.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.NONE.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.JAVA.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.JS.getName(), new JsLanguageHelper()); mapping.put(SyntaxType.PHP.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.PY.getName(), new PyLanguageHelper()); mapping.put(SyntaxType.XML.getName(), new NoneLanguageHelper()); mapping.put(SyntaxType.YAML.getName(), new NoneLanguageHelper()); } public static LanguageHelper getHelper(SyntaxType type) { if (instance == null) { instance = new LanguageHelperResolver(); } return instance.resolve(type.getName()); } private LanguageHelper resolve(String typeName) { LanguageHelper result = mapping.get(typeName); Preconditions.checkNotNull(result, "can't resolve language helper"); 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/code/autocomplete/AbstractTrie.java
client/src/main/java/com/google/collide/client/code/autocomplete/AbstractTrie.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Trie-based implementation of the prefix index. * * @param <T> value object type */ public class AbstractTrie<T> implements PrefixIndex<T> { // TODO: This member should be static and unmodifiable. private final JsonArray<T> emptyList = JsonCollections.createArray(); private TrieNode<T> root; public AbstractTrie() { clear(); } public TrieNode<T> getRoot() { return root; } public void clear() { this.root = TrieNode.<T>makeNode(""); } /** * @return {@code true} is this trie is empty */ public boolean isEmpty() { return this.root.getChildren().isEmpty(); } public TrieNode<T> put(String key, T value) { return insertIntoTrie(key, root, value); } @Override public JsonArray<T> search(String prefix) { TrieNode<T> searchRoot = findNode(prefix, root); return (searchRoot == null) ? emptyList : collectSubtree(searchRoot); } /** * Returns all leaf nodes from a subtree rooted by {@code searchRoot} node * and restricted with a {@code stopFunction} * * @param searchRoot node to start from * @return all leaf nodes in the matching subtree */ public static <T> JsonArray<T> collectSubtree(TrieNode<T> searchRoot) { JsonArray<TrieNode<T>> leaves = JsonCollections.createArray(); getAllLeavesInSubtree(searchRoot, leaves); JsonArray<T> result = JsonCollections.createArray(); for (int i = 0; i < leaves.size(); i++) { result.add(leaves.get(i).getValue()); } return result; } /** * Traverses the subtree rooted at {@code root} and collects all nodes in the * subtree that are leaves (i.e., valid elements, not only prefixes). * * @param root a node in the trie from which to start collecting * @param leaves output array */ private static <T> void getAllLeavesInSubtree(TrieNode<T> root, JsonArray<TrieNode<T>> leaves) { if (root.getIsLeaf()) { leaves.add(root); } for (int i = 0, size = root.getChildren().size(); i < size; i++) { TrieNode<T> child = root.getChildren().get(i); getAllLeavesInSubtree(child, leaves); } } private TrieNode<T> insertIntoTrie(String prefix, TrieNode<T> node, T value) { String nodePrefix = node.getPrefix(); if (nodePrefix.equals(prefix)) { node.setValue(value); return node; } else { TrieNode<T> branch = node.findInsertionBranch(prefix); if (branch != null) { return insertIntoTrie(prefix, branch, value); } else { // create new trie nodes JsonArray<TrieNode<T>> suffixChain = makeSuffixChain( node, prefix.substring(nodePrefix.length()), value); return suffixChain.peek(); } } } /** * Inserts a chain of children into the given node. * * @param root node to insert into * @param suffix suffix of the last node in the chain * @param value value of the last node in the chain * @return the inserted chain in direct order (from the root to the leaf) */ JsonArray<TrieNode<T>> makeSuffixChain(TrieNode<T> root, String suffix, T value) { JsonArray<TrieNode<T>> result = JsonCollections.createArray(); String rootPrefix = root.getPrefix(); for (int i = 1, suffixSize = suffix.length(); i <= suffixSize; i++) { String newPrefix = rootPrefix + suffix.substring(0, i); TrieNode<T> newNode = TrieNode.makeNode(newPrefix); result.add(newNode); root.addChild(newNode); root = newNode; } root.setValue(value); return result; } /** * Searches the subtree rooted at {@code searchRoot} for a node * corresponding to the prefix. * * There can only ever be one such node, or zero. If no node is found, returns * null. * * Note that the {@code prefix} is relative to the whole trie root, not * to the {@code searchRoot}. * * @param prefix the prefix to be found * @param searchRoot the root of the subtree that is searched * @return the node in the tree corresponding to prefix, or null if no such * node exists */ public static <T> TrieNode<T> findNode(String prefix, TrieNode<T> searchRoot) { Preconditions.checkNotNull(prefix); if (prefix.equals(searchRoot.getPrefix())) { return searchRoot; } TrieNode<T> closestAncestor = findClosestAncestor(prefix, searchRoot); return (closestAncestor.getPrefix().equals(prefix)) ? closestAncestor : null; } /** * Finds the closest ancestor of a search key. Formally it returns * a node x, such that: {@code prefix.startsWith(x.prefix)} * and there is no other node y, such that * {@code (prefix.startsWith(y.prefix) and y.prefix.length > x.prefix)} * * @param key search key * @param searchRoot node to start from * @return closest ancestor */ static <T> TrieNode<T> findClosestAncestor(String key, TrieNode<T> searchRoot) { Preconditions.checkNotNull(key); Preconditions.checkArgument(key.startsWith(searchRoot.getPrefix()), "key=%s root prefix=%s", key, searchRoot.getPrefix()); TrieNode<T> result = searchRoot; for (TrieNode<T> child = searchRoot; child != null; child = child.findInsertionBranch(key)) { result = child; } 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/code/autocomplete/SignalEventEssence.java
client/src/main/java/com/google/collide/client/code/autocomplete/SignalEventEssence.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import org.waveprotocol.wave.client.common.util.SignalEvent; import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType; import com.google.common.annotations.VisibleForTesting; // TODO: Replace with CharCodeWithModifiers. /** * Immutable holder of essential properties of * {@link SignalEvent} */ public class SignalEventEssence { public final int keyCode; public final boolean ctrlKey; public final boolean altKey; public final boolean shiftKey; public final boolean metaKey; public final KeySignalType type; @VisibleForTesting public SignalEventEssence(int keyCode, boolean ctrlKey, boolean altKey, boolean shiftKey, boolean metaKey, KeySignalType type) { this.keyCode = keyCode; this.ctrlKey = ctrlKey; this.altKey = altKey; this.shiftKey = shiftKey; this.metaKey = metaKey; this.type = type; } @VisibleForTesting public SignalEventEssence(int keyCode) { this(keyCode, false, false, false, false, KeySignalType.INPUT); } // TODO: Replace additional constructors with static methods. public SignalEventEssence(SignalEvent source) { this(source.getKeyCode(), source.getCtrlKey(), source.getAltKey(), source.getShiftKey(), source.getMetaKey(), source.getKeySignalType()); } public char getChar() { if (ctrlKey || altKey || metaKey || (type != KeySignalType.INPUT)) { return 0; } return (char) keyCode; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/DefaultAutocompleteResult.java
client/src/main/java/com/google/collide/client/code/autocomplete/DefaultAutocompleteResult.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import static com.google.collide.shared.document.util.PositionUtils.getPosition; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.EditorDocumentMutator; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.logging.Log; import com.google.collide.shared.document.Position; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * Implementation that allows to apply most common autocompletions. * */ public class DefaultAutocompleteResult implements AutocompleteResult { /** * Empty result. * * <ul> * <li>if there is no selection - does nothing * <li>if something is selected - deletes selected text * </ul> */ public static final DefaultAutocompleteResult EMPTY = new DefaultAutocompleteResult( "", 0, 0, 0, 0, PopupAction.CLOSE, ""); /** * Result that moves cursor to the right on 1 character and closes popup. * * <p>This result is used to bypass unintended user input. For example, when * user enters quote twice, first quote is explicitly doubled, and the * second one must be bypassed. */ public static final DefaultAutocompleteResult PASS_CHAR = new DefaultAutocompleteResult( "", 1, 0, 0, 0, PopupAction.CLOSE, ""); /** * Number of symbols to expand selection to the left before replacement. */ private final int backspaceCount; /** * Number of symbols to expand selection to the right before replacement. */ private final int deleteCount; /** * Text to be inserted at cursor position. */ private final String autocompletionText; /** * Number of chars, relative to beginning of replacement to move cursor right. */ private final int jumpLength; /** * Length of selection (in chars) before cursor position after jump. */ private final int selectionCount; /** * String that guards from applying result when context has changed. * * <p>{@link Autocompleter#applyChanges} checks that text before selection * (cursor) is the same as {@link #preContentSuffix} and refuses to apply * result if it's not truth. * * <p>If suffix is matched, then it is removed. That way one can replace * template shortcut with real template content. */ private final String preContentSuffix; /** * Action over popup when completion is applied. */ private final PopupAction popupAction; public DefaultAutocompleteResult(String autocompletionText, int jumpLength, int backspaceCount, int selectionCount, int deleteCount, PopupAction popupAction, String preContentSuffix) { Preconditions.checkState(jumpLength >= 0, "negative jump length"); Preconditions.checkState(backspaceCount >= 0, "negative backspace count"); Preconditions.checkState(selectionCount >= 0, "negative select count"); Preconditions.checkState(deleteCount >= 0, "negative delete count"); Preconditions.checkState(selectionCount <= jumpLength, "select count > jump length"); this.autocompletionText = autocompletionText; this.jumpLength = jumpLength; this.backspaceCount = backspaceCount; this.selectionCount = selectionCount; this.deleteCount = deleteCount; this.popupAction = popupAction; this.preContentSuffix = preContentSuffix; } /** * Creates simple textual insertion result. * * <p>Created instance describes insertion of specified text with matching * (see {@link #preContentSuffix}), without additional deletions and without * selection; after applying insertion popup is closed. */ public DefaultAutocompleteResult(String autocompletionText, String preContentSuffix, int jumpLength) { this(autocompletionText, jumpLength, 0, 0, 0, PopupAction.CLOSE, preContentSuffix); } @VisibleForTesting public String getAutocompletionText() { return autocompletionText; } @VisibleForTesting public int getJumpLength() { return jumpLength; } @VisibleForTesting public int getBackspaceCount() { return backspaceCount; } @VisibleForTesting public int getDeleteCount() { return deleteCount; } @Override public PopupAction getPopupAction() { return popupAction; } @Override public void apply(Editor editor) { SelectionModel selection = editor.getSelection(); Position[] selectionRange = selection.getSelectionRange(false); boolean selectionChanged = false; // 1) New beginning of selection based on suffix-matching and // backspaceCount Position selectionStart = selectionRange[0]; int selectionStartColumn = selectionStart.getColumn(); String textBefore = selectionStart.getLine().getText().substring(0, selectionStartColumn); if (!textBefore.endsWith(preContentSuffix)) { Log.warn(getClass(), "expected suffix [" + preContentSuffix + "] do not match [" + textBefore + "]"); return; } int matchCount = preContentSuffix.length(); int leftOffset = backspaceCount + matchCount; if (leftOffset > 0) { selectionStart = getPosition(selectionStart, -leftOffset); selectionChanged = true; } // 2) Calculate end of selection Position selectionEnd = selectionRange[1]; if (deleteCount > 0) { selectionEnd = getPosition(selectionEnd, deleteCount); selectionChanged = true; } // 3) Set selection it was changed. if (selectionChanged) { selection.setSelection(selectionStart.getLineInfo(), selectionStart.getColumn(), selectionEnd.getLineInfo(), selectionEnd.getColumn()); } // 4) Replace selection EditorDocumentMutator mutator = editor.getEditorDocumentMutator(); if (selection.hasSelection() || autocompletionText.length() > 0) { mutator.insertText(selectionStart.getLine(), selectionStart.getLineNumber(), selectionStart.getColumn(), autocompletionText); } // 5) Move cursor / set final selection selectionEnd = getPosition(selectionStart, jumpLength); if (selectionCount == 0) { selection.setCursorPosition(selectionEnd.getLineInfo(), selectionEnd.getColumn()); } else { selectionStart = getPosition(selectionStart, jumpLength - selectionCount); selection.setSelection(selectionStart.getLineInfo(), selectionStart.getColumn(), selectionEnd.getLineInfo(), selectionEnd.getColumn()); } } @Override public String toString() { return "SimpleAutocompleteResult{" + "backspaceCount=" + backspaceCount + ", deleteCount=" + deleteCount + ", autocompletionText='" + autocompletionText + '\'' + ", jumpLength=" + jumpLength + ", selectionCount=" + selectionCount + ", expectedSuffix='" + preContentSuffix + '\'' + ", popupAction=" + popupAction + '}'; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/AutocompleterCallback.java
client/src/main/java/com/google/collide/client/code/autocomplete/AutocompleterCallback.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; /** * Interface for connecting controller to the UI. * */ interface AutocompleterCallback { /** * Schedule completion request again, to show updated proposals */ void rescheduleCompletionRequest(); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/CodeAnalyzer.java
client/src/main/java/com/google/collide/client/code/autocomplete/CodeAnalyzer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import javax.annotation.Nonnull; import com.google.collide.codemirror2.Token; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; /** * Interface that presents code analyzing facilities. */ public interface CodeAnalyzer { /** * Prepares for new iteration of parsing. */ void onBeforeParse(); /** * Analyzes tokens and updates line meta-information. * * @param previousLine line that precedes line being parsed * @param line line being parsed * @param tokens tokens collected on the line */ void onParseLine(TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens); /** * Cleans up and perform batch operations at the end of parsing iteration. */ void onAfterParse(); /** * Cleans up meta-information for detached lines. * * @param deletedLines lines that are now detached */ void onLinesDeleted(JsonArray<TaggableLine> deletedLines); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/TrieNode.java
client/src/main/java/com/google/collide/client/code/autocomplete/TrieNode.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * A node in a trie that can be used for efficient autocompletion lookup. * * @param <T> value object type */ public final class TrieNode<T> { private final String prefix; private final JsonArray<TrieNode<T>> children; private T value; private TrieNode(String prefix) { this.prefix = prefix; this.value = null; this.children = JsonCollections.createArray(); } public static <T> TrieNode<T> makeNode(String prefix) { return new TrieNode<T>(prefix); } public JsonArray<TrieNode<T>> getChildren() { return children; } TrieNode<T> findInsertionBranch(String prefix) { for (int i = 0, size = children.size(); i < size; i++) { TrieNode<T> child = children.get(i); if (prefix.startsWith(child.getPrefix())) { return child; } } return null; } public void addChild(TrieNode<T> child) { children.add(child); } public boolean getIsLeaf() { return this.value != null; } public String getPrefix() { return this.prefix; } public void setValue(T value) { this.value = value; } public T getValue() { return this.value; } @Override public String toString() { return this.prefix; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/AutocompleteController.java
client/src/main/java/com/google/collide/client/code/autocomplete/AutocompleteController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.editor.selection.SelectionModel; import com.google.common.base.Preconditions; /** * Mediator that encapsulates data of the current autocomplete session and * provides an interface to populate autocompletion <b>asynchronously</b>. */ public class AutocompleteController { /** * Instance that performs all language specific logic. */ private LanguageSpecificAutocompleter languageAutocompleter; /** * Callback to {@link Autocompleter} instance methods, */ private AutocompleterCallback autocompleterCallback; public AutocompleteController(LanguageSpecificAutocompleter languageAutocompleter, AutocompleterCallback callback) { Preconditions.checkNotNull(languageAutocompleter); Preconditions.checkNotNull(callback); this.languageAutocompleter = languageAutocompleter; this.autocompleterCallback = callback; } /** * @return the language-specific autocontroller */ public LanguageSpecificAutocompleter getLanguageSpecificAutocompleter() { return languageAutocompleter; } /** * Calculates the completion result for the selected proposal. * * @param proposal proposal item selected by user */ AutocompleteResult finish(ProposalWithContext proposal) { AutocompleteResult result = languageAutocompleter.computeAutocompletionResult(proposal); pause(); return result; } boolean isAttached() { return languageAutocompleter != null; } /** * This method execution is scheduled from UI when it needs to * show completions. * * @param trigger event that triggered autocomplete request * (typically Ctrl+Space press) */ AutocompleteProposals start(SelectionModel selection, SignalEventEssence trigger) { Preconditions.checkNotNull(languageAutocompleter); languageAutocompleter.start(); return languageAutocompleter.findAutocompletions(selection, trigger); } /** * Stops language specific autocompleter and unbounds it from this controller. * * <p>{@link #languageAutocompleter} and {@link #autocompleterCallback} * are assigned {@code null} to avoid further interaction. */ void detach() { languageAutocompleter.detach(); languageAutocompleter = null; autocompleterCallback = null; } /** * Pauses language specific autocompleter. * * <p>This should be called after the dismission of the autocomplete box. */ void pause() { languageAutocompleter.pause(); } /** * Transfers request for updating proposals list. */ void scheduleRequestForUpdatedProposals() { autocompleterCallback.rescheduleCompletionRequest(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/NoneAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/NoneAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.codemirror2.SyntaxType; import com.google.common.annotations.VisibleForTesting; /** * Implementation that do not propose completions. */ public class NoneAutocompleter extends LanguageSpecificAutocompleter { private static NoneAutocompleter instance; public static NoneAutocompleter getInstance() { if (instance == null) { instance = new NoneAutocompleter(SyntaxType.NONE); } return instance; } @VisibleForTesting NoneAutocompleter(SyntaxType mode) { super(mode); } @Override public AutocompleteResult computeAutocompletionResult( AutocompleteProposals.ProposalWithContext proposal) { throw new IllegalStateException("This method should not be invoked"); } @Override public AutocompleteProposals findAutocompletions(SelectionModel selection, SignalEventEssence trigger) { return AutocompleteProposals.EMPTY; } @Override public void cleanup() { // 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/code/autocomplete/LanguageSpecificAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/LanguageSpecificAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.PathUtil; import com.google.collide.codemirror2.SyntaxType; import com.google.common.base.Preconditions; /** * Base class for language-specific autocompleters. * * <p>State transitions:<ol> * <li> {@link #LanguageSpecificAutocompleter} -> (2) * <li> {@link #attach} -> (3) or (8) * <li> {@link #getExplicitAction} -> (4) or (7) or (8) * <li> {@link #start} -> (5) or (8) * <li> {@link #findAutocompletions} -> (5) or (6) or (7) or (8) * <li> {@link #computeAutocompletionResult} -> (5) or (6) or (7) or (8) * <li> {@link #pause} -> (3) or (8) * <li> {@link #detach()} * </ol> */ public abstract class LanguageSpecificAutocompleter { /** * Enumeration of types of actions preformed on keypress. */ public enum ExplicitActionType { /** * Default behaviour (just append char). */ DEFAULT, /** * Append char and open autocompletion box. */ DEFERRED_COMPLETE, /** * Do not append char, use explicit autocompletion. */ EXPLICIT_COMPLETE, /** * Append char and close autocompletion box. */ CLOSE_POPUP } /** * Bean that holds explicit action type, and optional explicit autocompletion. */ public static class ExplicitAction { public static final ExplicitAction DEFAULT = new ExplicitAction( ExplicitActionType.DEFAULT, null); public static final ExplicitAction DEFERRED_COMPLETE = new ExplicitAction( ExplicitActionType.DEFERRED_COMPLETE, null); public static final ExplicitAction CLOSE_POPUP = new ExplicitAction( ExplicitActionType.CLOSE_POPUP, null); private final ExplicitActionType type; private final AutocompleteResult explicitAutocompletion; public ExplicitAction(AutocompleteResult explicitAutocompletion) { this(ExplicitActionType.EXPLICIT_COMPLETE, explicitAutocompletion); } public ExplicitAction(ExplicitActionType type, AutocompleteResult explicitAutocompletion) { this.type = type; this.explicitAutocompletion = explicitAutocompletion; } public ExplicitActionType getType() { return type; } public AutocompleteResult getExplicitAutocompletion() { return explicitAutocompletion; } } private AutocompleteController controller; private boolean isPaused; private final SyntaxType mode; private DocumentParser documentParser; protected LanguageSpecificAutocompleter(SyntaxType mode) { Preconditions.checkNotNull(mode); this.mode = mode; } /** * Computes the full autocompletion for a selected proposal. * * <p>A full autocompletion may include such things as closing tags or braces. * In complex substitution case the number of indexes the caret should jump * after the autocompletion is complete is also computed. * * @param proposal proposal selected by user * @return value object with information for applying changes */ public abstract AutocompleteResult computeAutocompletionResult(ProposalWithContext proposal); /** * Finds autocompletions for a given completion query. * * @param selection used to obtain current cursor position and selection * @param trigger used to request different lists of proposals * @return POJO holding array of autocompletion proposals. */ public abstract AutocompleteProposals findAutocompletions( SelectionModel selection, SignalEventEssence trigger); /** * Cleanup before instance is dismissed. */ public abstract void cleanup(); /** * Prepare instance for the new autocompletion life cycle. * * <p>No completions are requested yet, but the completer can prepare * itself (e.g. pre-fetch data). */ protected void attach( DocumentParser parser, AutocompleteController controller, PathUtil filePath) { Preconditions.checkNotNull(parser); documentParser = parser; this.controller = controller; isPaused = true; } /** * Specifies the behavior of this controller on signal events (not text * changes). * * <p>Ctrl-space event is processed directly and not passed to this * method. * * <p>Key press in not applied to document yet, so be careful when analyse * text around cursor. */ protected ExplicitAction getExplicitAction(SelectionModel selectionModel, SignalEventEssence signal, boolean popupIsShown) { return ExplicitAction.DEFAULT; } protected void start() { isPaused = false; } protected void pause() { isPaused = true; } /** * Indicates the end of this autocompleter lifecycle. * * <p>User switched to other file and is not willing to see any proposals * from this completer. */ protected void detach() { pause(); this.controller = null; } /** * Invoked by implementations to provide asynchronously obtained proposals. */ protected final void scheduleRequestForUpdatedProposals() { if (!isPaused) { controller.scheduleRequestForUpdatedProposals(); } } protected SyntaxType getMode() { return mode; } @Nonnull protected DocumentParser getParser() { return Preconditions.checkNotNull(documentParser); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/AutocompleteProposal.java
client/src/main/java/com/google/collide/client/code/autocomplete/AutocompleteProposal.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import java.util.Comparator; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.Utils; /** * Structure holding autocomplete proposal and additional metainformation * (currently filename where the proposal comes from). */ public class AutocompleteProposal { public static final Comparator<AutocompleteProposal> LEXICOGRAPHICAL_COMPARATOR = new Comparator<AutocompleteProposal>() { @Override public int compare(AutocompleteProposal first, AutocompleteProposal second) { // We assume that proposal never return null as label. return first.getLabel().compareToIgnoreCase(second.getLabel()); } }; protected final String name; protected final PathUtil path; public AutocompleteProposal(String name) { this(name, PathUtil.EMPTY_PATH); } public AutocompleteProposal(String name, PathUtil path) { assert name != null; this.name = name; this.path = path; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof AutocompleteProposal) { AutocompleteProposal that = (AutocompleteProposal) obj; if (!this.name.equals(that.name)) { return false; } if (Utils.equalsOrNull(this.path, that.path)) { return true; } return false; } else { return false; } } public String getName() { return name; } public PathUtil getPath() { return path; } @Override public int hashCode() { return this.name.hashCode() + (31 * this.path.hashCode()); } @Override public String toString() { return this.name + " :" + this.path.getPathString(); } public String getLabel() { return name; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/Autocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/Autocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import javax.annotation.Nonnull; import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction; import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.LimitedContextFilePrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.ParsingTask; import com.google.collide.client.code.autocomplete.codegraph.js.JsAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.js.JsIndexUpdater; import com.google.collide.client.code.autocomplete.codegraph.py.PyAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.py.PyIndexUpdater; import com.google.collide.client.code.autocomplete.css.CssAutocompleter; import com.google.collide.client.code.autocomplete.html.HtmlAutocompleter; import com.google.collide.client.code.autocomplete.html.XmlCodeAnalyzer; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.ScheduledCommandExecutor; import com.google.collide.client.util.collections.SkipListStringBag; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.codemirror2.Token; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; /** * Class to implement all the autocompletion support that is not specific to a * given language (e.g., css). */ public class Autocompleter { /** * Flag that specifies if proposals are filtered case-insensitively. * * <p>Once, this constant should become configuration option. */ public static final boolean CASE_INSENSITIVE = true; /** * Constant which limits number of results returned by * {@link LimitedContextFilePrefixIndex}. */ private static final int LOCAL_PREFIX_INDEX_LIMIT = 50; private static final XmlCodeAnalyzer XML_CODE_ANALYZER = new XmlCodeAnalyzer(); private final SkipListStringBag localPrefixIndexStorage; private final ParsingTask localPrefixIndexUpdater; private final PyIndexUpdater pyIndexUpdater; private final JsIndexUpdater jsIndexUpdater; private final HtmlAutocompleter htmlAutocompleter; private final CssAutocompleter cssAutocompleter; private final CodeGraphAutocompleter jsAutocompleter; private final CodeGraphAutocompleter pyAutocompleter; /** * Key that triggered autocomplete box opening. */ private SignalEventEssence boxTrigger; /** * Proxy that distributes notifications to all code analyzers. */ private final CodeAnalyzer distributingCodeAnalyzer = new CodeAnalyzer() { @Override public void onBeforeParse() { XML_CODE_ANALYZER.onBeforeParse(); localPrefixIndexUpdater.onBeforeParse(); pyIndexUpdater.onBeforeParse(); jsIndexUpdater.onBeforeParse(); } @Override public void onParseLine( TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens) { LanguageSpecificAutocompleter languageAutocompleter = getLanguageSpecificAutocompleter(); if (htmlAutocompleter == languageAutocompleter) { htmlAutocompleter.updateModeAnchors(line, tokens); XML_CODE_ANALYZER.onParseLine(previousLine, line, tokens); localPrefixIndexUpdater.onParseLine(previousLine, line, tokens); jsIndexUpdater.onParseLine(previousLine, line, tokens); } else if (pyAutocompleter == languageAutocompleter) { localPrefixIndexUpdater.onParseLine(previousLine, line, tokens); pyIndexUpdater.onParseLine(previousLine, line, tokens); } else if (jsAutocompleter == languageAutocompleter) { localPrefixIndexUpdater.onParseLine(previousLine, line, tokens); jsIndexUpdater.onParseLine(previousLine, line, tokens); } } @Override public void onAfterParse() { XML_CODE_ANALYZER.onAfterParse(); localPrefixIndexUpdater.onAfterParse(); pyIndexUpdater.onAfterParse(); jsIndexUpdater.onAfterParse(); } @Override public void onLinesDeleted(JsonArray<TaggableLine> deletedLines) { XML_CODE_ANALYZER.onLinesDeleted(deletedLines); localPrefixIndexUpdater.onLinesDeleted(deletedLines); pyIndexUpdater.onLinesDeleted(deletedLines); jsIndexUpdater.onLinesDeleted(deletedLines); } }; private class OnSelectCommand extends ScheduledCommandExecutor { private ProposalWithContext selectedProposal; @Override protected void execute() { Preconditions.checkNotNull(selectedProposal); reallyFinishAutocompletion(selectedProposal); selectedProposal = null; } public void scheduleAutocompletion(ProposalWithContext selectedProposal) { Preconditions.checkNotNull(selectedProposal); this.selectedProposal = selectedProposal; scheduleDeferred(); } } private final Editor editor; private boolean isAutocompleteInsertion = false; private AutocompleteController autocompleteController; private final AutocompleteBox popup; /** * Refreshes autocomplete popup contents (if it is displayed). * * <p>This method should be called when the code is modified. */ public void refresh() { if (autocompleteController == null) { return; } if (isAutocompleteInsertion) { return; } if (popup.isShowing()) { scheduleRequestAutocomplete(); } } /** * Callback passed to {@link AutocompleteController}. */ private final AutocompleterCallback callback = new AutocompleterCallback() { @Override public void rescheduleCompletionRequest() { scheduleRequestAutocomplete(); } }; private final OnSelectCommand onSelectCommand = new OnSelectCommand(); public static Autocompleter create( Editor editor, CubeClient cubeClient, final AutocompleteBox popup) { SkipListStringBag localPrefixIndexStorage = new SkipListStringBag(); LimitedContextFilePrefixIndex limitedContextFilePrefixIndex = new LimitedContextFilePrefixIndex( LOCAL_PREFIX_INDEX_LIMIT, localPrefixIndexStorage); CssAutocompleter cssAutocompleter = CssAutocompleter.create(); CodeGraphAutocompleter jsAutocompleter = JsAutocompleter.create( cubeClient, limitedContextFilePrefixIndex); HtmlAutocompleter htmlAutocompleter = HtmlAutocompleter.create( cssAutocompleter, jsAutocompleter); CodeGraphAutocompleter pyAutocompleter = PyAutocompleter.create( cubeClient, limitedContextFilePrefixIndex); PyIndexUpdater pyIndexUpdater = new PyIndexUpdater(); JsIndexUpdater jsIndexUpdater = new JsIndexUpdater(); return new Autocompleter(editor, popup, localPrefixIndexStorage, htmlAutocompleter, cssAutocompleter, jsAutocompleter, pyAutocompleter, pyIndexUpdater, jsIndexUpdater); } @VisibleForTesting Autocompleter(Editor editor, final AutocompleteBox popup, SkipListStringBag localPrefixIndexStorage, HtmlAutocompleter htmlAutocompleter, CssAutocompleter cssAutocompleter, CodeGraphAutocompleter jsAutocompleter, CodeGraphAutocompleter pyAutocompleter, PyIndexUpdater pyIndexUpdater, JsIndexUpdater jsIndexUpdater) { this.editor = editor; this.localPrefixIndexStorage = localPrefixIndexStorage; this.pyIndexUpdater = pyIndexUpdater; this.jsIndexUpdater = jsIndexUpdater; this.localPrefixIndexUpdater = new ParsingTask(localPrefixIndexStorage); this.cssAutocompleter = cssAutocompleter; this.jsAutocompleter = jsAutocompleter; this.htmlAutocompleter = htmlAutocompleter; this.pyAutocompleter = pyAutocompleter; this.popup = popup; popup.setDelegate(new AutocompleteBox.Events() { @Override public void onSelect(ProposalWithContext proposal) { if (AutocompleteProposals.NO_OP == proposal) { return; } // This is called on UI click - so surely we want popup to disappear. // TODO: It's a quick-fix; uncomment when autocompletions // become completer state free. //dismissAutocompleteBox(); onSelectCommand.scheduleAutocompletion(proposal); } @Override public void onCancel() { dismissAutocompleteBox(); } }); } /** * Asks popup and language-specific autocompleter to process key press * and schedules corresponding autocompletion requests, if required. * * @return {@code true} if event shouldn't be further processed / bubbled */ public boolean processKeyPress(SignalEventEssence trigger) { if (autocompleteController == null) { return false; } if (popup.isShowing() && popup.consumeKeySignal(trigger)) { return true; } if (isCtrlSpace(trigger)) { boxTrigger = trigger; scheduleRequestAutocomplete(); return true; } LanguageSpecificAutocompleter autocompleter = getLanguageSpecificAutocompleter(); ExplicitAction action = autocompleter.getExplicitAction(editor.getSelection(), trigger, popup.isShowing()); switch (action.getType()) { case EXPLICIT_COMPLETE: boxTrigger = null; performExplicitCompletion(action.getExplicitAutocompletion()); return true; case DEFERRED_COMPLETE: boxTrigger = trigger; scheduleRequestAutocomplete(); return false; case CLOSE_POPUP: dismissAutocompleteBox(); return false; default: return false; } } private static boolean isCtrlSpace(SignalEventEssence trigger) { return trigger.ctrlKey && (trigger.keyCode == ' ') && (trigger.type == KeySignalType.INPUT); } /** * Hides popup and prevents further activity. */ private void stop() { dismissAutocompleteBox(); if (this.autocompleteController != null) { this.autocompleteController.detach(); this.autocompleteController = null; } localPrefixIndexStorage.clear(); } /** * Setups for the document to be auto-completed. */ public void reset(PathUtil filePath, DocumentParser parser) { Preconditions.checkNotNull(filePath); Preconditions.checkNotNull(parser); stop(); LanguageSpecificAutocompleter autocompleter = getAutocompleter(parser.getSyntaxType()); this.autocompleteController = new AutocompleteController(autocompleter, callback); autocompleter.attach(parser, autocompleteController, filePath); } @VisibleForTesting protected LanguageSpecificAutocompleter getLanguageSpecificAutocompleter() { Preconditions.checkNotNull(autocompleteController); return autocompleteController.getLanguageSpecificAutocompleter(); } @VisibleForTesting AutocompleteController getController() { return autocompleteController; } @VisibleForTesting SyntaxType getMode() { return (autocompleteController == null) ? SyntaxType.NONE : autocompleteController.getLanguageSpecificAutocompleter().getMode(); } /** * Applies textual and UI changes specified with {@link AutocompleteResult}. */ @SuppressWarnings("incomplete-switch") private void applyChanges(AutocompleteResult result) { switch (result.getPopupAction()) { case CLOSE: dismissAutocompleteBox(); break; case OPEN: scheduleRequestAutocomplete(); break; } isAutocompleteInsertion = true; try { result.apply(editor); } finally { isAutocompleteInsertion = false; } } /** * Fetch changes from controller for selected proposal, hide popup; * apply changes. * * @param proposal proposal item selected by user */ @VisibleForTesting void reallyFinishAutocompletion(ProposalWithContext proposal) { applyChanges(autocompleteController.finish(proposal)); } /** * Dismisses the autocomplete box. * * <p>This is called when the user hits escape or types until * there are no more autocompletions or navigates away * from the autocompletion box position. */ public void dismissAutocompleteBox() { popup.dismiss(); boxTrigger = null; if (autocompleteController != null) { autocompleteController.pause(); } } /** * Schedules an asynchronous call to compute and display / perform * appropriate autocompletion proposals. */ private void scheduleRequestAutocomplete() { final SignalEventEssence trigger = boxTrigger; final AutocompleteController controller = autocompleteController; Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { requestAutocomplete(controller, trigger); } }); } private void performExplicitCompletion(AutocompleteResult completion) { Preconditions.checkState(!isAutocompleteInsertion); applyChanges(completion); } @VisibleForTesting void requestAutocomplete(AutocompleteController controller, SignalEventEssence trigger) { if (!controller.isAttached()) { return; } // TODO: If there is only one proposal that gives us nothing // then there are no proposals! AutocompleteProposals proposals = controller.start(editor.getSelection(), trigger); if (AutocompleteProposals.PARSING == proposals && popup.isShowing()) { // Do nothing to avoid flickering. } else if (!proposals.isEmpty()) { popup.positionAndShow(proposals); } else { dismissAutocompleteBox(); } } @VisibleForTesting protected LanguageSpecificAutocompleter getAutocompleter(SyntaxType mode) { switch (mode) { case HTML: return htmlAutocompleter; case JS: return jsAutocompleter; case CSS: return cssAutocompleter; case PY: return pyAutocompleter; default: return NoneAutocompleter.getInstance(); } } public void cleanup() { stop(); jsAutocompleter.cleanup(); pyAutocompleter.cleanup(); } public CodeAnalyzer getCodeAnalyzer() { return distributingCodeAnalyzer; } /** * Refreshes proposals list after cursor has been processed by parser. */ public void onCursorLineParsed() { refresh(); } public void onDocumentParsingFinished() { refresh(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/AutocompleteBox.java
client/src/main/java/com/google/collide/client/code/autocomplete/AutocompleteBox.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; /** * Interface used to isolate {@link Autocompleter} from UI implementation. */ public interface AutocompleteBox { /** * Interface that allows {@link AutocompleteBox} implementations * to fire back (UI event based) notifications. */ interface Events { /** * Performs autocompletion selected by user. */ void onSelect(ProposalWithContext proposal); /** * Closes autocompletion box. */ void onCancel(); } /** * Tests if box is shown. */ boolean isShowing(); /** * Reacts on keyboard event. * * @return {@code true} if event should not be processed further. */ boolean consumeKeySignal(SignalEventEssence signal); /** * Sets delegate instance that is notified on user actions. */ void setDelegate(Events delegate); /** * Hides component. */ void dismiss(); /** * Shows component (if hidden) and updates proposals list. */ void positionAndShow(AutocompleteProposals items); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/AutocompleteProposals.java
client/src/main/java/com/google/collide/client/code/autocomplete/AutocompleteProposals.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Object that holds a set of proposals produced by * {@link LanguageSpecificAutocompleter}. * * <p>In this object proposals are kept together with object that allows * construction of {@link AutocompleteResult} (some kind of context). * */ public class AutocompleteProposals { /** * Class that holds common information for the set of proposals. */ public static class Context { private final String triggeringString; private final int indent; public Context(String triggeringString) { this(triggeringString, 0); } public Context(String triggeringString, int indent) { this.triggeringString = triggeringString; this.indent = indent; } public String getTriggeringString() { return triggeringString; } public int getIndent() { return indent; } } /** * Immutable bean that holds both selected item and context object for * computing autocompletion. */ public static class ProposalWithContext { private final SyntaxType syntaxType; private final AutocompleteProposal proposal; private final Context context; public ProposalWithContext(SyntaxType syntaxType, AutocompleteProposal proposal, Context context) { this.syntaxType = syntaxType; this.proposal = proposal; this.context = context; } public SyntaxType getSyntaxType() { return syntaxType; } public AutocompleteProposal getItem() { return proposal; } public Context getContext() { return context; } } public static final AutocompleteProposals EMPTY = new AutocompleteProposals(""); public static final AutocompleteProposals PARSING; public static final ProposalWithContext NO_OP = // Using SyntaxType.NONE because for no-op the mode does not matter. new ProposalWithContext(SyntaxType.NONE, null, null); static { JsonArray<AutocompleteProposal> pleaseWaitItems = JsonCollections.createArray(); pleaseWaitItems.add(new AutocompleteProposal("...parsing...")); // Using SyntaxType.NONE because for parsing proposals the mode does not // matter. PARSING = new AutocompleteProposals(SyntaxType.NONE, "", pleaseWaitItems) { @Override public ProposalWithContext select(AutocompleteProposal proposal) { return NO_OP; } }; } private SyntaxType syntaxType; protected final Context context; private final String hint; protected final JsonArray<AutocompleteProposal> items; private AutocompleteProposals(String context) { // Using SyntaxType.NONE because for empty proposals the mode does not // matter. this(SyntaxType.NONE, context, JsonCollections.<AutocompleteProposal>createArray()); } public AutocompleteProposals(SyntaxType syntaxType, String triggeringString, JsonArray<AutocompleteProposal> items) { this(syntaxType, triggeringString, items, null); } public AutocompleteProposals(SyntaxType syntaxType, String triggeringString, JsonArray<AutocompleteProposal> items, String hint) { this(syntaxType, new Context(triggeringString), items, hint); } /** * Constructs proposals object. * * <p>Side effect: items in the given array are reordered. */ public AutocompleteProposals(SyntaxType syntaxType, Context context, JsonArray<AutocompleteProposal> items, String hint) { Preconditions.checkNotNull(context); Preconditions.checkNotNull(items); this.syntaxType = syntaxType; this.context = context; this.items = items; this.hint = hint; items.sort(AutocompleteProposal.LEXICOGRAPHICAL_COMPARATOR); } public AutocompleteProposal get(int index) { return items.get(index); } public int size() { return items.size(); } /** * Returns the autocomplete proposals as a JsonArray. * * Note: The returned array should not be modified; it is the same instance as * the internal array. */ public JsonArray<AutocompleteProposal> getItems() { return items; } public boolean isEmpty() { return items.isEmpty(); } public final ProposalWithContext select(int index) { return select(items.get(index)); } public ProposalWithContext select(AutocompleteProposal proposal) { Preconditions.checkState(items.contains(proposal)); return new ProposalWithContext(syntaxType, proposal, context); } public String getHint() { return hint; } public SyntaxType getSyntaxType() { return syntaxType; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/AutocompleteResult.java
client/src/main/java/com/google/collide/client/code/autocomplete/AutocompleteResult.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.client.editor.Editor; /** * Object that encapsulates knowledge about changes to be applied to document. */ public interface AutocompleteResult { /** * Enumeration of action types performed when result is applied. */ public enum PopupAction { /** * Close popup (if opened). */ CLOSE, /** * Open popup. */ OPEN, /** * Leave popup as it is. */ NONE } PopupAction getPopupAction(); /** * Applies changes to document. * * @param editor document container. */ void apply(Editor editor); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/PrefixIndex.java
client/src/main/java/com/google/collide/client/code/autocomplete/PrefixIndex.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete; import com.google.collide.json.shared.JsonArray; /** * Interface of the index structure which supports search by the key prefix. * * @param <T> value data type */ public interface PrefixIndex<T> { /** * Searches values by the key prefix. * * @param prefix search key prefix * @return values having keys prefixed with {@code prefix} */ JsonArray<? extends T> search(String prefix); }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/integration/AutocompleteUiController.java
client/src/main/java/com/google/collide/client/code/autocomplete/integration/AutocompleteUiController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.integration; import org.waveprotocol.wave.client.common.util.SignalEvent; import collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.code.autocomplete.AutocompleteBox; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.FocusManager; import com.google.collide.client.ui.list.SimpleList; import com.google.collide.client.ui.list.SimpleList.View; import com.google.collide.client.ui.menu.AutoHideController; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.anchor.ReadOnlyAnchor; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.resources.client.CssResource; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.html.ClientRect; import elemental.html.TableCellElement; import elemental.html.TableElement; /** * A controller for managing the UI for showing autocomplete proposals. * */ public class AutocompleteUiController implements AutocompleteBox { public interface Resources extends SimpleList.Resources { @Source("AutocompleteComponent.css") Css autocompleteComponentCss(); } public interface Css extends CssResource { String cappedProposalLabel(); String proposalLabel(); String proposalGroup(); String container(); String items(); String hint(); int maxHeight(); } private static final int MAX_COMPLETIONS_TO_SHOW = 100; private static final AutocompleteProposal CAPPED_INDICATOR = new AutocompleteProposal(""); private final SimpleList.ListItemRenderer<AutocompleteProposal> listItemRenderer = new SimpleList.ListItemRenderer<AutocompleteProposal>() { @Override public void render(Element itemElement, AutocompleteProposal itemData) { TableCellElement label = Elements.createTDElement(css.proposalLabel()); TableCellElement group = Elements.createTDElement(css.proposalGroup()); if (itemData != CAPPED_INDICATOR) { label.setTextContent(itemData.getLabel()); group.setTextContent(itemData.getPath().getPathString()); } else { label.setTextContent("Type for more results"); label.addClassName(css.cappedProposalLabel()); } itemElement.appendChild(label); itemElement.appendChild(group); } @Override public Element createElement() { return Elements.createTRElement(); } }; private final SimpleList.ListEventDelegate<AutocompleteProposal> listDelegate = new SimpleList.ListEventDelegate<AutocompleteProposal>() { @Override public void onListItemClicked(Element itemElement, AutocompleteProposal itemData) { Preconditions.checkNotNull(delegate); if (itemData == CAPPED_INDICATOR) { return; } delegate.onSelect(autocompleteProposals.select(itemData)); } }; private final AutoHideController autoHideController; private final Css css; private final SimpleList<AutocompleteProposal> list; private Events delegate; private final Editor editor; private final Element box; private final Element container; private final Element hint; /** Will be non-null when the popup is showing */ private ReadOnlyAnchor anchor; /** * True to force the layout above the anchor, false to layout below. This * should be set when showing from the hidden state. It's used to keep * the position consistent while the box is visible. */ private boolean positionAbove; /** * The currently displayed proposals. This may contain more proposals than actually shown since we * cap the maximum number of visible proposals. This will be null if the UI is not showing. */ private AutocompleteProposals autocompleteProposals; public AutocompleteUiController(Editor editor, Resources res) { this.editor = editor; this.css = res.autocompleteComponentCss(); box = Elements.createDivElement(); // Prevent our mouse events from going to the editor DomUtils.stopMousePropagation(box); TableElement tableElement = Elements.createTableElement(); tableElement.setClassName(css.items()); container = Elements.createDivElement(css.container()); DomUtils.preventExcessiveScrollingPropagation(container); container.appendChild(tableElement); box.appendChild(container); hint = Elements.createDivElement(css.hint()); CssUtils.setDisplayVisibility2(hint, false); box.appendChild(hint); list = SimpleList.create((View) box, container, tableElement, res.defaultSimpleListCss(), listItemRenderer, listDelegate); autoHideController = AutoHideController.create(box); autoHideController.setCaptureOutsideClickOnClose(false); autoHideController.setDelay(-1); } @Override public boolean isShowing() { return autoHideController.isShowing(); } @Override public boolean consumeKeySignal(SignalEventEssence signal) { Preconditions.checkState(isShowing()); Preconditions.checkNotNull(delegate); if ((signal.keyCode == KeyCodes.KEY_TAB) || (signal.keyCode == KeyCodes.KEY_ENTER)) { delegate.onSelect(autocompleteProposals.select(list.getSelectionModel().getSelectedItem())); return true; } if (signal.keyCode == KeyCodes.KEY_ESCAPE) { delegate.onCancel(); return true; } if (signal.type != SignalEvent.KeySignalType.NAVIGATION) { return false; } if ((signal.keyCode == KeyCodes.KEY_DOWN)) { list.getSelectionModel().selectNext(); return true; } if (signal.keyCode == KeyCodes.KEY_UP) { list.getSelectionModel().selectPrevious(); return true; } if ((signal.keyCode == KeyCodes.KEY_LEFT) || (signal.keyCode == KeyCodes.KEY_RIGHT)) { delegate.onCancel(); return true; } if (signal.keyCode == KeyCodes.KEY_PAGEUP) { list.getSelectionModel().selectPreviousPage(); return true; } if (signal.keyCode == KeyCodes.KEY_PAGEDOWN) { list.getSelectionModel().selectNextPage(); return true; } return false; } @Override public void setDelegate(Events delegate) { this.delegate = delegate; } @Override public void dismiss() { boolean hadFocus = list.hasFocus(); autoHideController.hide(); if (anchor != null) { editor.getBuffer().removeAnchoredElement(anchor, autoHideController.getView().getElement()); anchor = null; } autocompleteProposals = null; FocusManager focusManager = editor.getFocusManager(); if (hadFocus && !focusManager.hasFocus()) { focusManager.focus(); } } @Override public void positionAndShow(AutocompleteProposals items) { this.autocompleteProposals = items; this.anchor = editor.getSelection().getCursorAnchor(); boolean showingFromHidden = !autoHideController.isShowing(); if (showingFromHidden) { list.getSelectionModel().clearSelection(); } final JsonArray<AutocompleteProposal> itemsToDisplay; if (items.size() <= MAX_COMPLETIONS_TO_SHOW) { itemsToDisplay = items.getItems(); } else { itemsToDisplay = items.getItems().slice(0, MAX_COMPLETIONS_TO_SHOW); itemsToDisplay.add(CAPPED_INDICATOR); } list.render(itemsToDisplay); if (list.getSelectionModel().getSelectedItem() == null) { list.getSelectionModel().setSelectedItem(0); } String hintText = items.getHint(); if (hintText == null) { hint.setTextContent(""); CssUtils.setDisplayVisibility2(hint, false); } else { hint.setTextContent(hintText); CssUtils.setDisplayVisibility2(hint, true); } autoHideController.show(); editor.getBuffer().addAnchoredElement(anchor, box); ensureRootElementWillBeOnScreen(showingFromHidden); } private void ensureRootElementWillBeOnScreen(boolean showingFromHidden) { // Remove any max-heights so we can get its desired height container.getStyle().removeProperty("max-height"); ClientRect bounds = box.getBoundingClientRect(); int height = (int) bounds.getHeight(); int delta = height - (int) container.getBoundingClientRect().getHeight(); ClientRect bufferBounds = editor.getBuffer().getBoundingClientRect(); int lineHeight = editor.getBuffer().getEditorLineHeight(); int lineTop = (int) bounds.getTop() - CssUtils.parsePixels(box.getStyle().getMarginTop()); int spaceAbove = lineTop - (int) bufferBounds.getTop(); int spaceBelow = (int) bufferBounds.getBottom() - lineTop - lineHeight; if (showingFromHidden) { // If it was already showing, we don't adjust the positioning. positionAbove = spaceAbove >= css.maxHeight() && spaceBelow < css.maxHeight(); } // Get available height. int maxHeight = positionAbove ? spaceAbove : spaceBelow; // Restrict to specified height. maxHeight = Math.min(maxHeight, css.maxHeight()); // Fit to content size. maxHeight = Math.min(maxHeight, height); container.getStyle().setProperty( "max-height", (maxHeight - delta) + CSSStyleDeclaration.Unit.PX); int marginTop = positionAbove ? -maxHeight : lineHeight; box.getStyle().setMarginTop(marginTop, CSSStyleDeclaration.Unit.PX); } @VisibleForTesting SimpleList<AutocompleteProposal> getList() { return list; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/integration/TaggableLineUtil.java
client/src/main/java/com/google/collide/client/code/autocomplete/integration/TaggableLineUtil.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.integration; import javax.annotation.Nonnull; import com.google.collide.shared.TaggableLine; import com.google.collide.shared.document.Line; /** * {@link com.google.collide.shared.TaggableLine} utility class. * */ public class TaggableLineUtil { private static final TaggableLine NULL_PREVIOUS_LINE = new TaggableLine() { @Override public <T> T getTag(String key) { return null; } @Override public <T> void putTag(String key, T value) { throw new IllegalStateException("Can't put tag to null line"); } @Override public TaggableLine getPreviousLine() { throw new IllegalStateException("There is no minus 2'nd line"); } @Override public boolean isFirstLine() { // It is line before the first line, so it is not first. return false; } @Override public boolean isLastLine() { // For sure we have at least one more line (first line). return false; } }; @Nonnull public static TaggableLine getPreviousLine(@Nonnull Line line) { Line previousLine = line.getPreviousLine(); if (previousLine != null) { return previousLine; } else { return NULL_PREVIOUS_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/code/autocomplete/integration/DocumentParserListenerAdapter.java
client/src/main/java/com/google/collide/client/code/autocomplete/integration/DocumentParserListenerAdapter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.integration; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.Autocompleter; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.codemirror2.Token; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; import com.google.collide.shared.document.Line; /** * Listener implementation that adapts messages for {@link Autocompleter}. */ public class DocumentParserListenerAdapter implements DocumentParser.Listener { private final Autocompleter autocompleter; private final Editor editor; private boolean asyncParsing; boolean cursorLineParsed; boolean documentParsingFinished; public DocumentParserListenerAdapter(Autocompleter autocompleter, Editor editor) { this.autocompleter = autocompleter; this.editor = editor; } @Override public void onIterationStart(int lineNumber) { asyncParsing = true; cursorLineParsed = false; documentParsingFinished = false; autocompleter.getCodeAnalyzer().onBeforeParse(); } @Override public void onIterationFinish() { asyncParsing = false; autocompleter.getCodeAnalyzer().onAfterParse(); if (documentParsingFinished) { autocompleter.onDocumentParsingFinished(); } if (cursorLineParsed) { autocompleter.onCursorLineParsed(); } } @Override public void onDocumentLineParsed(Line line, int lineNumber, @Nonnull JsonArray<Token> tokens) { if (asyncParsing) { TaggableLine previousLine = TaggableLineUtil.getPreviousLine(line); autocompleter.getCodeAnalyzer().onParseLine(previousLine, line, tokens); if (editor.getSelection().getCursorLineNumber() == lineNumber) { cursorLineParsed = true; } if (line.getNextLine() == null) { documentParsingFinished = true; } } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/integration/AutocompleterFacade.java
client/src/main/java/com/google/collide/client/code/autocomplete/integration/AutocompleterFacade.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.integration; import org.waveprotocol.wave.client.common.util.SignalEvent; import com.google.collide.client.Resources; import com.google.collide.client.code.autocomplete.Autocompleter; import com.google.collide.client.code.autocomplete.SignalEventEssence; 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.util.PathUtil; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar.RemoverManager; /** * This class isolates {@link Autocompleter} from the UI. */ public class AutocompleterFacade { private final Autocompleter autocompleter; private final Editor editor; private final RemoverManager instanceListeners = new RemoverManager(); private final RemoverManager documentListeners = new RemoverManager(); private final Document.LineListener lineListener = new Document.LineListener() { @Override public void onLineAdded(Document document, int lineNumber, JsonArray<Line> addedLines) { // Do nothing. } @Override public void onLineRemoved(Document document, int lineNumber, JsonArray<Line> removedLines) { JsonArray<TaggableLine> deletedLines = JsonCollections.createArray(); for (final Line line : removedLines.asIterable()) { deletedLines.add(line); } autocompleter.getCodeAnalyzer().onLinesDeleted(deletedLines); } }; /** * A listener that receives and translates keyboard events. */ private final Editor.KeyListener keyListener = new Editor.KeyListener() { @Override public boolean onKeyPress(SignalEvent event) { return autocompleter.processKeyPress(new SignalEventEssence(event)); } }; /** * A listener that dismisses the autocomplete box when the editor is scrolled. */ private final Buffer.ScrollListener dismissingScrollListener = new Buffer.ScrollListener() { @Override public void onScroll(Buffer buffer, int scrollTop) { autocompleter.dismissAutocompleteBox(); } }; /** * A listener for user modifications in the editor. */ private final Editor.TextListener textListener = new Editor.TextListener() { @Override public void onTextChange(TextChange textChange) { autocompleter.refresh(); } }; private final DocumentParser.Listener parseListener; public static AutocompleterFacade create( Editor editor, CubeClient cubeClient, Resources resources) { AutocompleteUiController popup = new AutocompleteUiController(editor, resources); Autocompleter autocompleter = Autocompleter.create(editor, cubeClient, popup); return new AutocompleterFacade(editor, autocompleter); } public AutocompleterFacade(Editor editor, Autocompleter autocompleter) { this.editor = editor; this.autocompleter = autocompleter; this.parseListener = new DocumentParserListenerAdapter(autocompleter, editor); instanceListeners.track(editor.getTextListenerRegistrar().add(textListener)); instanceListeners.track(editor.getKeyListenerRegistrar().add(keyListener)); instanceListeners.track( editor.getBuffer().getScrollListenerRegistrar().add(dismissingScrollListener)); } public void cleanup() { pause(); instanceListeners.remove(); autocompleter.cleanup(); } private void pause() { documentListeners.remove(); } public void editorContentsReplaced(PathUtil path, DocumentParser parser) { pause(); documentListeners.track(editor.getDocument().getLineListenerRegistrar().add(lineListener)); documentListeners.track(parser.getListenerRegistrar().add(parseListener)); autocompleter.reset(path, parser); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/CodeGraphAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CodeGraphAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import com.google.collide.client.code.autocomplete.AutocompleteController; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.code.autocomplete.AutocompleteResult; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.PathUtil; import com.google.collide.codemirror2.SyntaxType; import com.google.common.base.Preconditions; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; /** * Implements autocompleter for abstract language statements. */ public class CodeGraphAutocompleter extends LanguageSpecificAutocompleter { private static final RegExp ID_REGEXP = RegExp.compile("[a-zA-Z\\$_][a-zA-Z\\$_0-9]*$"); private ScopeTrieBuilder scopeTrieBuilder; private final CodeGraphSource codeGraphSource; private final ProposalBuilder proposalBuilder; private final ExplicitAutocompleter explicitAutocompleter; private final LimitedContextFilePrefixIndex contextFilePrefixIndex; private final Runnable codeGraphUpdateListener = new Runnable() { @Override public void run() { scopeTrieBuilder.setCodeGraph(codeGraphSource.constructCodeGraph()); scheduleRequestForUpdatedProposals(); } }; public CodeGraphAutocompleter(SyntaxType mode, ProposalBuilder proposalBuilder, CubeClient cubeClient, LimitedContextFilePrefixIndex contextFilePrefixIndex, ExplicitAutocompleter explicitAutocompleter) { super(mode); this.explicitAutocompleter = explicitAutocompleter; this.proposalBuilder = proposalBuilder; this.contextFilePrefixIndex = contextFilePrefixIndex; this.codeGraphSource = new CodeGraphSource(cubeClient, codeGraphUpdateListener); } @Override public AutocompleteResult computeAutocompletionResult(ProposalWithContext selected) { AutocompleteProposals.Context context = selected.getContext(); String triggeringString = context.getTriggeringString(); AutocompleteProposal proposal = selected.getItem(); if (proposal instanceof TemplateProposal) { TemplateProposal templateProposal = (TemplateProposal) proposal; return templateProposal.buildResult(triggeringString, context.getIndent()); } Preconditions.checkArgument(proposal instanceof CodeGraphProposal); CodeGraphProposal selectedProposal = (CodeGraphProposal) proposal; return proposalBuilder.computeAutocompletionResult(selectedProposal, triggeringString); } /** * Finds autocompletions for a given completion query. * * <p>This method is triggered when:<ul> * <li>popup is hidden and user press ctrl-space (event consumed) * <li><b>or</b> popup is hidden and user press "." (dot applied) * <li><b>or</b> popup is shown * </ul> */ @Override public AutocompleteProposals findAutocompletions( SelectionModel selection, SignalEventEssence trigger) { Preconditions.checkNotNull(scopeTrieBuilder); if (selection.hasSelection()) { // Do not autocomplete JS/PY when something is selected. return AutocompleteProposals.EMPTY; } if (trigger == null || trigger.altKey || !trigger.shiftKey) { return proposalBuilder.getProposals(getMode(), getParser(), selection, scopeTrieBuilder); } return contextFilePrefixIndex.search(getMode(), calculateTriggeringString(selection)); } private static String calculateTriggeringString(SelectionModel selection) { String cursorLine = selection.getCursorLine().getText(); int cursorColumn = selection.getCursorColumn(); MatchResult matchResult = ID_REGEXP.exec(cursorLine.substring(0, cursorColumn)); if (matchResult == null) { return ""; } return matchResult.getGroup(0); } @Override protected void pause() { super.pause(); codeGraphSource.setPaused(true); } @Override protected void start() { super.start(); codeGraphSource.setPaused(false); Preconditions.checkNotNull(scopeTrieBuilder); if (codeGraphSource.hasUpdate()) { scopeTrieBuilder.setCodeGraph(codeGraphSource.constructCodeGraph()); } } @Override public ExplicitAction getExplicitAction(SelectionModel selectionModel, SignalEventEssence signal, boolean popupIsShown) { return explicitAutocompleter.getExplicitAction( selectionModel, signal, popupIsShown, getParser()); } @Override public void attach( DocumentParser parser, AutocompleteController controller, PathUtil filePath) { super.attach(parser, controller, filePath); CodeFile contextFile = new CodeFile(filePath); scopeTrieBuilder = new ScopeTrieBuilder(contextFile, getMode()); scopeTrieBuilder.setCodeGraph(codeGraphSource.constructCodeGraph()); } @Override public void cleanup() { codeGraphSource.cleanup(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CodeGraphProposal.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CodeGraphProposal.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.util.PathUtil; /** * Extended structure: also holds if proposal case is "function"-case. */ public class CodeGraphProposal extends AutocompleteProposal { private final boolean isFunction; private String labelCache; public CodeGraphProposal(String name) { super(name); isFunction = false; } public CodeGraphProposal(String name, PathUtil path, boolean function) { super(name, path); this.isFunction = function; } public boolean isFunction() { return isFunction; } @Override public String getLabel() { if (labelCache == null) { labelCache = name + (isFunction ? "()" : ""); } return labelCache; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/LimitedContextFilePrefixIndex.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/LimitedContextFilePrefixIndex.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.util.collections.SkipListStringBag; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Object that holds / searches IDs. * */ public class LimitedContextFilePrefixIndex { private final SkipListStringBag items; private final int limit; public LimitedContextFilePrefixIndex(int limit, SkipListStringBag items) { Preconditions.checkNotNull(items); this.limit = limit; this.items = items; } public AutocompleteProposals search(SyntaxType syntaxType, String prefix) { final JsonArray<AutocompleteProposal> result = JsonCollections.createArray(); boolean hasMore = false; for (String id : items.search(prefix)) { if (!id.startsWith(prefix)) { break; } if (result.size() == limit) { hasMore = true; break; } result.add(new CodeGraphProposal(id)); } String hint = hasMore ? "First " + limit + " possible completions are shown." : null; return new AutocompleteProposals(syntaxType, prefix, result, hint); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/ExplicitAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/ExplicitAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import static com.google.collide.client.code.autocomplete.AutocompleteResult.PopupAction.CLOSE; import static com.google.collide.client.code.autocomplete.codegraph.ParseUtils.Context.IN_CODE; import static com.google.collide.client.code.autocomplete.codegraph.ParseUtils.Context.IN_COMMENT; import static com.google.collide.client.code.autocomplete.codegraph.ParseUtils.Context.IN_STRING; import static com.google.collide.client.code.autocomplete.codegraph.ParseUtils.Context.NOT_PARSED; import static com.google.collide.codemirror2.TokenType.STRING; import static com.google.gwt.event.dom.client.KeyCodes.KEY_BACKSPACE; import static org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType.DELETE; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.codemirror2.State; 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.Position; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * Object that answers question about explicit actions and autocompletions. * */ public class ExplicitAutocompleter { private static final ExplicitAction RESULT_DELETE_AND_BACKSPACE = new ExplicitAction( new DefaultAutocompleteResult("", 0, 1, 0, 1, CLOSE, "")); /** * Compute left-trimmed text before position. * * @param position point of interest * @return beginning of line with removed spaces */ static String leftTrimmedLineTextBeforePosition(Position position) { return position.getLine().getText().substring(0, position.getColumn()).replaceAll("^\\s+", ""); } /** * Compute text after position. * * @param position point of interest * @return tail of line */ static String textAfterPosition(Position position) { return position.getLine().getText().substring(position.getColumn()); } static String textBeforePosition(Position position) { return position.getLine().getText().substring(0, position.getColumn()); } private boolean isExplicitDoublingChar(char keyCode) { return "(\"){'}[]".indexOf(keyCode) != -1; } protected ExplicitAction getExplicitAction(SelectionModel selectionModel, SignalEventEssence signal, boolean popupIsShown, @Nonnull DocumentParser parser) { char key = signal.getChar(); if (!popupIsShown && key == '.') { return ExplicitAction.DEFERRED_COMPLETE; } if (isExplicitDoublingChar(key)) { return getExplicitDoublingAutocompletion(signal, selectionModel, parser); } if (DELETE == signal.type && KEY_BACKSPACE == signal.keyCode && !signal.ctrlKey && !signal.altKey && !signal.shiftKey && !signal.metaKey) { return getExplicitBackspaceAutocompletion(selectionModel, parser); } if (Character.isLetterOrDigit(key) || key == '_' || key == 0) { return ExplicitAction.DEFAULT; } return popupIsShown ? ExplicitAction.CLOSE_POPUP : ExplicitAction.DEFAULT; } /** * Calculates explicit autocompletion result for "backspace" press. * * <p>This method works in assumption that there is no selection. * * <p>One "dangerous" case is when user press "backspace" at the very * beginning of the document. * * @return result that performs "del" or "del+bs" or nothing */ private ExplicitAction getExplicitBackspaceAutocompletion( SelectionModel selection, @Nonnull DocumentParser parser) { if (selection.hasSelection()) { return ExplicitAction.DEFAULT; } Position cursor = selection.getCursorPosition(); String textToCursor = leftTrimmedLineTextBeforePosition(cursor); String textAfterCursor = textAfterPosition(cursor); ParseUtils.ExtendedParseResult<State> extendedParseResult = ParseUtils .getExtendedParseResult(State.class, parser, cursor); ParseUtils.Context context = extendedParseResult.getContext(); char right = textAfterCursor.length() > 0 ? textAfterCursor.charAt(0) : 0; if (context == IN_STRING) { // This means that full token contains only string quotes. if ((String.valueOf(right)).equals(extendedParseResult.getLastTokenValue())) { return RESULT_DELETE_AND_BACKSPACE; } } else if (context == IN_CODE) { char left = textToCursor.length() > 0 ? textToCursor.charAt(textToCursor.length() - 1) : 0; if (left == '(' && right == ')') { return RESULT_DELETE_AND_BACKSPACE; } else if (left == '{' && right == '}') { return RESULT_DELETE_AND_BACKSPACE; } else if (left == '[' && right == ']') { return RESULT_DELETE_AND_BACKSPACE; } } return ExplicitAction.DEFAULT; } private ExplicitAction getExplicitDoublingAutocompletion( SignalEventEssence trigger, SelectionModel selection, @Nonnull DocumentParser parser) { Position[] selectionRange = selection.getSelectionRange(false); ParseUtils.ExtendedParseResult<State> extendedParseResult = ParseUtils .getExtendedParseResult(State.class, parser, selectionRange[0]); ParseUtils.Context context = extendedParseResult.getContext(); char key = trigger.getChar(); Preconditions.checkState(key != 0); if (context == NOT_PARSED || context == IN_COMMENT) { return ExplicitAction.DEFAULT; } String textAfterCursor = textAfterPosition(selectionRange[1]); int nextChar = -1; if (textAfterCursor.length() > 0) { nextChar = textAfterCursor.charAt(0); } boolean canPairParenthesis = nextChar == -1 || nextChar == ' ' || nextChar == ',' || nextChar == ';' || nextChar == '\n'; // TODO: Check if user has just fixed pairing? if (context != IN_STRING) { if ('(' == key && canPairParenthesis) { return new ExplicitAction(new DefaultAutocompleteResult("()", "", 1)); } else if ('[' == key && canPairParenthesis) { return new ExplicitAction(new DefaultAutocompleteResult("[]", "", 1)); } else if ('{' == key && canPairParenthesis) { return new ExplicitAction(new DefaultAutocompleteResult("{}", "", 1)); } else if ('"' == key || '\'' == key) { String doubleQuote = key + "" + key; if (!textBeforePosition(selectionRange[0]).endsWith(doubleQuote)) { return new ExplicitAction(new DefaultAutocompleteResult(doubleQuote, "", 1)); } } else if (!selection.hasSelection() && (key == nextChar) && (']' == key || ')' == key || '}' == key)) { // Testing what is more useful: pasting or passing. JsonArray<Token> tokens = parser.parseLineSync(selectionRange[0].getLine()); if (tokens != null) { int column = selectionRange[0].getColumn(); String closers = calculateClosingParens(tokens, column); String openers = calculateOpenParens(tokens, column); int match = StringUtils.findCommonPrefixLength(closers, openers); int newMatch = StringUtils.findCommonPrefixLength(key + closers, openers); if (newMatch <= match) { // With pasting results will be worse -> pass. return new ExplicitAction(DefaultAutocompleteResult.PASS_CHAR); } } } } else { if ((key == nextChar) && ('"' == key || '\'' == key)) { ParseResult<State> parseResult = parser.getState(State.class, selectionRange[0], key + " "); if (parseResult != null) { JsonArray<Token> tokens = parseResult.getTokens(); Preconditions.checkState(!tokens.isEmpty()); if (tokens.peek().getType() != STRING) { return new ExplicitAction(DefaultAutocompleteResult.PASS_CHAR); } } } } return ExplicitAction.DEFAULT; } @VisibleForTesting static String calculateOpenParens(JsonArray<Token> tokens, int column) { if (column == 0) { return ""; } JsonArray<String> parens = JsonCollections.createArray(); int colSum = 0; for (Token token : tokens.asIterable()) { String value = token.getValue(); if ("}".equals(value) || ")".equals(value) || "]".equals(value)) { if (parens.size() > 0) { if (value.equals(parens.peek())) { parens.pop(); } else { parens.clear(); } } } else if ("{".equals(value)) { parens.add("}"); } else if ("(".equals(value)) { parens.add(")"); } else if ("[".equals(value)) { parens.add("]"); } colSum += value.length(); if (colSum >= column) { break; } } parens.reverse(); return parens.join(""); } @VisibleForTesting static String calculateClosingParens(JsonArray<Token> tokens, int column) { StringBuilder result = new StringBuilder(); int colSum = 0; for (Token token : tokens.asIterable()) { String value = token.getValue(); if (colSum >= column) { if ("}".equals(value) || ")".equals(value) || "]".equals(value)) { result.append(value); } else if (token.getType() != TokenType.WHITESPACE) { break; } } colSum += value.length(); } return result.toString(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/TemplateProposal.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/TemplateProposal.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import static com.google.collide.client.code.autocomplete.AutocompleteResult.PopupAction.CLOSE; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteResult; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.shared.util.StringUtils; /** * Proposal that contains template and knows how to process it. * * <p>Template is a string which may contain the following wildcard symbols:<ul> * <li>%n - new line character with indentation to the level of * the inserting place; * <li>%i - additional indentation; * <li>%c - a point to place the cursor to after inserting. * </ul> */ public class TemplateProposal extends AutocompleteProposal { private final String template; public TemplateProposal(String name, String template) { super(name); this.template = template; } /** * Translates template to {@link AutocompleteResult}. */ public AutocompleteResult buildResult(String triggeringString, int indent) { String lineStart = "\n" + StringUtils.getSpaces(indent); String replaced = template .replace("%n", lineStart) .replace("%i", indent(lineStart)) .replace("%d", dedent(lineStart)); int pos = replaced.indexOf("%c"); pos = (pos == -1) ? replaced.length() : pos; String completion = replaced.replace("%c", ""); return new DefaultAutocompleteResult(completion, pos, 0, 0, 0, CLOSE, triggeringString); } /** * Adds an indentation to a given string. * * <p>We suppose extra indention to be double-space. */ private static String indent(String s) { return s + " "; } /** * Removes extra indention. * * <p>We suppose extra indention to be double-space. */ private static String dedent(String s) { if (s.endsWith(" ")) { return s.substring(0, s.length() - 2); } return s; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/CodeGraphPrefixIndex.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CodeGraphPrefixIndex.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.util.PathUtil; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.dto.CodeBlock; import com.google.collide.dto.CodeBlockAssociation; import com.google.collide.dto.CodeGraph; import com.google.collide.json.client.JsoArray; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.json.shared.JsonStringMap.IterationCallback; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; import com.google.common.base.Objects; import com.google.common.base.Preconditions; /** * Implements a prefix index over code graph. */ public class CodeGraphPrefixIndex implements PrefixIndex<CodeGraphProposal> { private final CodeGraph codeGraph; private final JsonStringMap<FileIndex> fileIdToData = JsonCollections.createMap(); private final JsonStringMap<String> filePathToId = JsonCollections.createMap(); private final PathUtil contextFilePath; private final boolean globalNamespace; private static String getFullId(FileIndex fileIndex, CodeBlock cb) { return fileIndex.fileCodeBlock.getId() + ":" + cb.getId(); } /** * Objects returned as search results. */ private static class CodeGraphProposalImpl extends CodeGraphProposal { private final CodeBlock codeBlock; private final FileIndex fileData; CodeGraphProposalImpl(CodeBlock codeBlock, String qname, FileIndex fileData) { super(qname, fileData.path, codeBlock.getBlockType() == CodeBlock.Type.VALUE_FUNCTION); this.codeBlock = codeBlock; this.fileData = fileData; } } /** * Keeps per-file indexing data structures. */ private static class FileIndex { /** * Code blocks are indexed with breadth-first queue */ private static class IndexQueueItem { final String fqnamePrefix; final JsonArray<CodeBlock> codeBlocks; IndexQueueItem(String prefix, JsonArray<CodeBlock> codeBlocks) { this.fqnamePrefix = prefix; this.codeBlocks = codeBlocks; } } private static final JsonArray<CodeBlockAssociation> EMPTY_LINKS_ARRAY = JsonCollections.createArray(); private final JsonStringMap<JsonArray<CodeBlockAssociation>> links = JsonCollections.createMap(); private final PathUtil path; private final CodeBlock fileCodeBlock; private final JsonStringMap<CodeBlock> codeBlocks = JsonCollections.createMap(); private final JsoArray<IndexQueueItem> indexQueue = JsoArray.create(); private final JsonStringMap<String> fqnames = JsonCollections.createMap(); FileIndex(CodeBlock fileCodeBlock, PathUtil path) { this.path = path; this.fileCodeBlock = fileCodeBlock; indexQueue.add(new IndexQueueItem(null, JsonCollections.createArray(fileCodeBlock))); } void addOutgoingLink(CodeBlockAssociation link) { String key = Objects.firstNonNull(link.getSourceLocalId(), ""); JsonArray<CodeBlockAssociation> linksArray = links.get(key); if (linksArray == null) { linksArray = JsonCollections.createArray(); links.put(key, linksArray); } linksArray.add(link); } JsonArray<CodeBlockAssociation> getOutgoingLinks(CodeBlock codeBlock) { String key = getMapKey(codeBlock); JsonArray<CodeBlockAssociation> result = links.get(key); return result == null ? EMPTY_LINKS_ARRAY : result; } CodeBlock findCodeBlock(String localId) { String key = localId == null ? "" : localId; CodeBlock result = getCodeBlock(key); if (result != null) { return result; } return indexUntil(key); } private CodeBlock getCodeBlock(String localId) { String key = localId == null ? "" : localId; return codeBlocks.get(key); } String getFqname(CodeBlock codeBlock) { return fqnames.get(getMapKey(codeBlock)); } String getFqname(String localId) { String key = localId == null ? "" : localId; return fqnames.get(key); } private CodeBlock indexUntil(String searchKey) { while (!indexQueue.isEmpty()) { IndexQueueItem head = indexQueue.shift(); String prefix = head.fqnamePrefix; if (!StringUtils.isNullOrEmpty(prefix)) { prefix = prefix + "."; } for (int i = 0; i < head.codeBlocks.size(); i++) { CodeBlock codeBlock = head.codeBlocks.get(i); String key = getMapKey(codeBlock); codeBlocks.put(key, codeBlock); String fqname = appendFqname(prefix, codeBlock); putFqname(codeBlock, fqname); indexQueue.add(new IndexQueueItem(fqname, codeBlock.getChildren())); } CodeBlock result = codeBlocks.get(searchKey); if (result != null) { return result; } } return null; } void putFqname(CodeBlock codeBlock, String fqname) { fqnames.put(getMapKey(codeBlock), fqname); } private String getMapKey(CodeBlock codeBlock) { return codeBlock == fileCodeBlock ? "" : codeBlock.getId(); } private String appendFqname(String prefix, CodeBlock codeBlock) { return (codeBlock == fileCodeBlock) ? "" : prefix + codeBlock.getName(); } } CodeGraphPrefixIndex(CodeGraph codeGraph, SyntaxType mode) { this(codeGraph, mode, null); } CodeGraphPrefixIndex(CodeGraph codeGraph, SyntaxType mode, PathUtil contextFilePath) { Preconditions.checkNotNull(codeGraph); Preconditions.checkNotNull(mode); this.codeGraph = codeGraph; this.contextFilePath = contextFilePath; this.globalNamespace = mode.hasGlobalNamespace() || contextFilePath == null; JsonStringMap<CodeBlock> codeBlockMap = codeGraph.getCodeBlockMap(); JsonArray<String> keys = codeBlockMap.getKeys(); for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); CodeBlock fileCodeBlock = codeBlockMap.get(key); SyntaxType fileMode = SyntaxType.syntaxTypeByFileName(fileCodeBlock.getName()); if (mode.equals(fileMode)) { FileIndex fileIndex = new FileIndex(fileCodeBlock, new PathUtil(fileCodeBlock.getName())); fileIdToData.put(fileCodeBlock.getId(), fileIndex); String filePath = fileIndex.path.getPathString(); String idList = filePathToId.get(filePath); if (idList != null) { idList += "," + fileCodeBlock.getId(); } else { idList = fileCodeBlock.getId(); } filePathToId.put(filePath, idList); } } CodeBlock defaultPackage = codeGraph.getDefaultPackage(); if (defaultPackage != null) { filePathToId.put("", defaultPackage.getId()); fileIdToData.put(defaultPackage.getId(), new FileIndex(defaultPackage, new PathUtil(""))); } } @Override public JsonArray<? extends CodeGraphProposal> search(final String query) { return searchRoot(query); } /** * Runs a query against all files in the code graph. * * @param query query to run * @return an array of code graph proposals matching the query */ private JsonArray<? extends CodeGraphProposal> searchRoot(final String query) { final JsonArray<CodeGraphProposalImpl> result = JsonCollections.createArray(); if (globalNamespace) { fileIdToData.iterate(new IterationCallback<FileIndex>() { @Override public void onIteration(String key, FileIndex value) { search(query, value.fileCodeBlock, value, result); } }); } else { String idList = filePathToId.get(contextFilePath.getPathString()); if (idList != null) { for (String id : StringUtils.split(idList, ",").asIterable()) { FileIndex fileIndex = fileIdToData.get(id); search(query, fileIndex.fileCodeBlock, fileIndex, result); } } } if (codeGraph.getDefaultPackage() != null) { search(query, codeGraph.getDefaultPackage(), fileIdToData.get(codeGraph.getDefaultPackage().getId()), result); } return result; } private void search(String query, CodeBlock root, FileIndex fileData, JsonArray<CodeGraphProposalImpl> result) { collectOutgoingLinks(codeGraph.getTypeAssociations()); collectOutgoingLinks(codeGraph.getInheritanceAssociations()); collectOutgoingLinks(codeGraph.getImportAssociations()); JsonArray<CodeGraphProposalImpl> linkSourceCandidates = JsonCollections.createArray(); linkSourceCandidates.add(new CodeGraphProposalImpl(root, "", fileData)); searchTree(query, "", root, fileData, false, linkSourceCandidates, result); searchLinks(query, linkSourceCandidates, result); } private void searchLinks(String query, JsonArray<CodeGraphProposalImpl> linkSourceCandidates, JsonArray<CodeGraphProposalImpl> result) { JsonStringSet visited = JsonCollections.createStringSet(); while (!linkSourceCandidates.isEmpty()) { JsonArray<CodeGraphProposalImpl> newCandidates = JsonCollections.createArray(); for (CodeGraphProposalImpl candidate : linkSourceCandidates.asIterable()) { CodeBlock codeBlock = candidate.codeBlock; JsonArray<CodeGraphProposalImpl> zeroBoundary = JsonCollections.createArray(); JsonArray<CodeGraphProposalImpl> epsilonBoundary = JsonCollections.createArray(); createBoundary(codeBlock, candidate.fileData, zeroBoundary, epsilonBoundary, visited); String linkAccessPrefix = candidate.getName(); if (linkAccessPrefix == null) { linkAccessPrefix = ""; } if (!StringUtils.isNullOrEmpty(linkAccessPrefix)) { linkAccessPrefix += "."; } for (CodeGraphProposalImpl zeroNeighbor : zeroBoundary.asIterable()) { searchTree(query, linkAccessPrefix, zeroNeighbor.codeBlock, zeroNeighbor.fileData, false, newCandidates, result); } for (CodeGraphProposalImpl epsilonNeighbor : epsilonBoundary.asIterable()) { String epsilonAccessPrefix = linkAccessPrefix; CodeBlock targetCodeBlock = epsilonNeighbor.codeBlock; if (targetCodeBlock.getBlockType() == CodeBlock.Type.VALUE_FILE) { epsilonAccessPrefix += truncateExtension(targetCodeBlock.getName()); } else { epsilonAccessPrefix += targetCodeBlock.getName(); } epsilonAccessPrefix += "."; searchTree(query, epsilonAccessPrefix, targetCodeBlock, epsilonNeighbor.fileData, false, newCandidates, result); } } linkSourceCandidates = newCandidates; } } /** * <p>This function recursively walks a code block tree from the given root * and matches its code blocks against the query. * * <p>Depending on whether strict or partial match is needed, it writes * to the output array {@code matched} those code blocks which have an access prefix * either exactly matching the query or starting with the query. * * <p>Code blocks which potentially may have matches in their subtrees are * collected in {@code visited} output array for further processing of their * outgoing links. */ private void searchTree(String query, String accessPrefix, CodeBlock root, FileIndex fileData, boolean strictMatch, JsonArray<CodeGraphProposalImpl> visited, JsonArray<CodeGraphProposalImpl> matched) { String lcQuery = query.toLowerCase(); String rootFqname = fileData.getFqname(root); JsonArray<CodeBlock> children = root.getChildren(); for (int i = 0; i < children.size(); i++) { CodeBlock child = children.get(i); if (fileData.getFqname(child) == null) { // It is just a side-effect for performance reasons. Since we're traversing // the tree anyway, why don't we fill in fqnames table at the same time? String childFqname = (rootFqname == null) ? child.getName() : rootFqname + "." + child.getName(); fileData.putFqname(child, childFqname); } final String childAccessPrefix = accessPrefix + child.getName(); final String lcChildAccessPrefix = childAccessPrefix.toLowerCase(); CodeGraphProposalImpl childProposal = new CodeGraphProposalImpl( child, childAccessPrefix, fileData); if (strictMatch && lcChildAccessPrefix.equals(lcQuery)) { // If we want a strict match then "foo.bar" child will match // "foo.bar" query but will not match "foo.b" matched.add(childProposal); } if (!strictMatch && lcChildAccessPrefix.startsWith(lcQuery)) { // If we don't need a strict match then "foo.bar." and "foo.baz." // both match query "foo.b" matched.add(childProposal); } if (lcQuery.startsWith(lcChildAccessPrefix + ".")) { // Children of "foo.bar." may or may not have matches for query "foo.bar.b" // but children of "foo.bar.baz" are all already matching "foo.bar.b" (and // we don't need to go deeper) while children of "foo.baz" can't match // "foo.bar.b" at all. if (visited != null) { visited.add(childProposal); } searchTree(query, childAccessPrefix + ".", child, fileData, strictMatch, visited, matched); } } } /** * Useful for debugging */ @SuppressWarnings("unused") private String linkToString(CodeBlockAssociation link) { FileIndex sourceFile = fileIdToData.get(link.getSourceFileId()); FileIndex targetFile = fileIdToData.get(link.getTargetFileId()); if (sourceFile == null || targetFile == null) { return "invalid link. source file=" + link.getSourceFileId() + " target file=" + link.getTargetFileId(); } return sourceFile.fileCodeBlock.getName() + ":" + sourceFile.getFqname(link.getSourceLocalId()) + " ==(" + link.getType() + ")==> " + targetFile.fileCodeBlock.getName() + ":" + targetFile.getFqname(link.getTargetLocalId()); } /** * Creates a boundary of a {@code root} code block. Boundary is a closure of * code blocks accessible from {@code root} code blocks via associations. * Since we have two types of associations, one where association target * is included into access path, and one where it is not, we partition * boundary code blocks into "epsilon" boundary and "zero" boundary * correspondingly. */ private void createBoundary(CodeBlock root, FileIndex fileData, final JsonArray<CodeGraphProposalImpl> zeroBoundary, JsonArray<CodeGraphProposalImpl> epsilonBoundary, JsonStringSet visited) { visited.add(getFullId(fileData, root)); final JsonArray<CodeBlockAssociation> queue = fileData.getOutgoingLinks(root).copy(); while (!queue.isEmpty()) { CodeBlockAssociation link = queue.splice(0, 1).pop(); FileIndex targetFileData = fileIdToData.get(link.getTargetFileId()); if (targetFileData == null) { continue; } CodeBlock targetCodeBlock = targetFileData.findCodeBlock(link.getTargetLocalId()); if (targetCodeBlock == null) { continue; } final String targetFqname = targetFileData.getFqname(targetCodeBlock); if (targetFqname == null) { if (targetCodeBlock.getBlockType() != CodeBlock.Type.VALUE_FILE) { throw new IllegalStateException( "type=" + CodeBlock.Type.valueOf(targetCodeBlock.getBlockType())); } continue; } String fullTargetId = getFullId(targetFileData, targetCodeBlock); if (visited.contains(fullTargetId)) { continue; } visited.add(fullTargetId); // We have found a CodeBlock which is a target of the concrete link. // We want to match children of this code block against the query, // but the problem is that the children may be defined in another file // or can even be spread over many files (which is the case in JS where // one can add a method to Document.prototype from anywhere). // So we need to run a tree query to find all code blocks with the // same fqname (called representatives below). if (link.getIsRootAssociation()) { epsilonBoundary.add(new CodeGraphProposalImpl( targetCodeBlock, targetFqname, targetFileData)); } else { final JsonArray<CodeGraphProposalImpl> fqnameRepresentatives = JsonCollections.createArray(); fileIdToData.iterate(new IterationCallback<FileIndex>() { @Override public void onIteration(String key, FileIndex value) { searchTree( targetFqname, "", value.fileCodeBlock, value, true, null, fqnameRepresentatives); for (int i = 0; i < fqnameRepresentatives.size(); i++) { CodeGraphProposalImpl representative = fqnameRepresentatives.get(i); queue.addAll(representative.fileData.getOutgoingLinks(representative.codeBlock)); zeroBoundary.add(representative); } } }); } } } private static String truncateExtension(String name) { PathUtil path = new PathUtil(name); String basename = path.getBaseName(); int lastDot = basename.lastIndexOf('.'); return (lastDot == -1) ? basename : basename.substring(0, lastDot); } /** * Scans the links array and distributes its elements over the files they * are going from. Clears the array when finished. * * @param links links array */ private void collectOutgoingLinks(JsonArray<? extends CodeBlockAssociation> links) { if (links == null) { return; } for (int i = 0, size = links.size(); i < size; i++) { CodeBlockAssociation link = links.get(i); FileIndex fileData = fileIdToData.get(link.getSourceFileId()); if (fileData != null) { fileData.addOutgoingLink(link); } } links.clear(); } public boolean isEmpty() { return fileIdToData.isEmpty(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/Position.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/Position.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.collide.client.code.autocomplete.codegraph; /** * Encapsulates (line, column) pair. */ public class Position implements Comparable<Position> { private final int line; private final int col; private Position(int line, int col) { this.line = line; this.col = col; } public int getLine() { return this.line; } public int getColumn() { return this.col; } @Override public String toString() { return "(" + line + ", " + col + ")"; } public static Position from(int line, int col) { return new Position(line, col); } @Override public int compareTo(Position o) { int result = this.line - o.line; return result == 0 ? this.col - o.col : 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/code/autocomplete/codegraph/CodeGraphSource.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CodeGraphSource.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; 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.dto.CodeBlock; import com.google.collide.dto.CodeGraph; import com.google.collide.dto.ImportAssociation; import com.google.collide.dto.InheritanceAssociation; import com.google.collide.dto.TypeAssociation; import com.google.collide.dto.client.DtoClientImpls.CodeGraphImpl; import com.google.collide.json.client.JsoArray; import com.google.collide.json.client.JsoStringMap; import com.google.common.annotations.VisibleForTesting; /** * Controls codegraph update process. Sends requests to the frontend, processes * the response and notifies the client if code graph has been updated. * */ class CodeGraphSource implements CubeUpdateListener { private final CubeClient cubeClient; private final Runnable updateListener; private boolean isPaused = true; /** * Flag that shows that instance received updates since last * {@link #constructCodeGraph()} invocation. */ private boolean hasUpdate; CodeGraphSource(CubeClient cubeClient, Runnable updateListener) { this.cubeClient = cubeClient; this.updateListener = updateListener; cubeClient.addListener(this); } @VisibleForTesting public boolean hasUpdate() { return hasUpdate; } CodeGraph constructCodeGraph() { CubeData data = cubeClient.getData(); hasUpdate = false; CodeGraphImpl result = CodeGraphImpl.make(); result.setCodeBlockMap(JsoStringMap.<CodeBlock>create()); result.setInheritanceAssociations(JsoArray.<InheritanceAssociation>create()); result.setTypeAssociations(JsoArray.<TypeAssociation>create()); result.setImportAssociations(JsoArray.<ImportAssociation>create()); CodeGraph fullGraph = data.getFullGraph(); CodeGraph workspaceTree = data.getWorkspaceTree(); CodeBlock fileTree = data.getFileTree(); CodeGraph libsSubgraph = data.getLibsSubgraph(); if (fullGraph != null) { mergeCodeGraph(fullGraph, result); } if (workspaceTree != null) { mergeCodeGraph(workspaceTree, result); } if (fileTree != null) { result.getCodeBlockMap().put(fileTree.getId(), fileTree); } if (libsSubgraph != null) { mergeCodeGraph(libsSubgraph, result); } return result; } private void mergeCodeGraph(CodeGraph from, CodeGraphImpl to) { to.getCodeBlockMap().putAll(from.getCodeBlockMap()); if (from.getInheritanceAssociations() != null) { to.getInheritanceAssociations().addAll(from.getInheritanceAssociations()); } if (from.getTypeAssociations() != null) { to.getTypeAssociations().addAll(from.getTypeAssociations()); } if (from.getImportAssociations() != null) { to.getImportAssociations().addAll(from.getImportAssociations()); } } void setPaused(boolean paused) { isPaused = paused; } void cleanup() { cubeClient.removeListener(this); } @Override public void onCubeResponse(CubeData data, CubeDataUpdates updates) { hasUpdate = true; if (!isPaused) { updateListener.run(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/ParsingTask.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/ParsingTask.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import static com.google.collide.codemirror2.TokenType.DEF; import static com.google.collide.codemirror2.TokenType.PROPERTY; import static com.google.collide.codemirror2.TokenType.VARIABLE; import static com.google.collide.codemirror2.TokenType.VARIABLE2; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.CodeAnalyzer; import com.google.collide.client.util.collections.SkipListStringBag; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; import com.google.collide.shared.util.JsonCollections; /** * This task filters out IDs from parse results and updates collection of * discovered IDs. * */ public class ParsingTask implements CodeAnalyzer { private static final String TAG_ID_LIST = ParsingTask.class.getName() + ".idList"; private final SkipListStringBag fileIndex; private final JsonArray<String> idsToRelease = JsonCollections.createArray(); @Override public void onLinesDeleted(JsonArray<TaggableLine> deletedLines) { for (TaggableLine line : deletedLines.asIterable()) { JsonArray<String> lineIds = line.getTag(TAG_ID_LIST); if (lineIds != null) { fileIndex.removeAll(lineIds); } } } public ParsingTask(SkipListStringBag fileIndex) { this.fileIndex = fileIndex; } @Override public void onBeforeParse() { } @Override public void onAfterParse() { fileIndex.removeAll(idsToRelease); idsToRelease.clear(); } @Override public void onParseLine( TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens) { JsonArray<String> lineIds = line.getTag(TAG_ID_LIST); if (lineIds == null) { lineIds = JsonCollections.createArray(); line.putTag(TAG_ID_LIST, lineIds); } idsToRelease.addAll(lineIds); lineIds.clear(); for (int i = 0, l = tokens.size(); i < l; i++) { Token token = tokens.get(i); TokenType type = token.getType(); if (type == VARIABLE || type == VARIABLE2 || type == PROPERTY || type == DEF) { String value = token.getValue(); if (value.length() > 2) { lineIds.add(value); } } // TODO: Process strings that look like ID. } fileIndex.addAll(lineIds); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/Scope.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/Scope.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import com.google.collide.dto.CodeBlock; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Represents parsed chunk of the source code. Encapsulates chunk boundaries, * identifiers found in the chunk and their positions. */ public class Scope { private final CodeBlock rootCodeBlock; private final JsonArray<Scope> subscopes = JsonCollections.createArray(); private Position endPos; private Position beginPos; Scope(CodeBlock codeBlock) { Preconditions.checkNotNull(codeBlock); this.rootCodeBlock = codeBlock; setBegin(Position.from(codeBlock.getStartLineNumber(), codeBlock.getStartColumn())); setEnd(Position.from(codeBlock.getEndLineNumber(), codeBlock.getEndColumn())); } @Override public String toString() { String bounds = " [(" + getBeginLineNumber() + "," + getBeginColumn() + "), (" + getEndLineNumber() + "," + getEndColumn() + ")]"; return CodeBlock.Type.valueOf(rootCodeBlock.getBlockType()) + " " + rootCodeBlock.getName() + bounds; } int getBeginColumn() { return beginPos.getColumn(); } int getBeginLineNumber() { return beginPos.getLine(); } CodeBlock getCodeBlock() { return rootCodeBlock; } int getEndColumn() { return endPos.getColumn(); } int getEndLineNumber() { return endPos.getLine(); } JsonArray<Scope> getSubscopes() { return subscopes; } public void setBegin(Position pos) { beginPos = pos; } public void setEnd(Position pos) { endPos = pos; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/ParseUtils.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/ParseUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import static com.google.collide.codemirror2.Token.LITERAL_PERIOD; import static com.google.collide.codemirror2.TokenType.NULL; import static com.google.collide.codemirror2.TokenType.REGEXP; import static com.google.collide.codemirror2.TokenType.STRING; import static com.google.collide.codemirror2.TokenType.VARIABLE; import static com.google.collide.codemirror2.TokenType.VARIABLE2; import static com.google.collide.codemirror2.TokenType.WHITESPACE; import javax.annotation.Nonnull; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.codemirror2.State; 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.Position; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Set of utilities to perform code parsing and parse results processing. */ public class ParseUtils { private static final String SPACE = " "; private static final String[] CONTEXT_START = new String[] {"[", "(", "{"}; private static final String SIMPLE_CONTEXT_END = "])"; private static final String CONTEXT_END = SIMPLE_CONTEXT_END + "}"; /** * Collect ids interleaved with periods, omitting parenthesis groups. * * @param tokens source tokens array; destroyed in runtime. * @param expectingPeriod state before parsing: * {@code true} if period token is expected * @param contextParts output collector; only ids are collected * @return state after parsing: {@code true} if period token is expected */ static boolean buildInvocationSequenceContext( JsonArray<Token> tokens, boolean expectingPeriod, JsonArray<String> contextParts) { // right-to-left tokens processing loop. while (!tokens.isEmpty()) { Token lastToken = tokens.pop(); TokenType lastTokenType = lastToken.getType(); String lastTokenValue = lastToken.getValue(); // Omit whitespaces. if (lastTokenType == WHITESPACE) { continue; } if (expectingPeriod) { // If we are expecting period, then no other tokens are allowed. if ((lastTokenType != NULL) || !LITERAL_PERIOD.equals(lastTokenValue)) { return expectingPeriod; } expectingPeriod = false; } else { // Not expecting period means that previously processed token (located // to the right of the current token) was not id. // That way we expect id or parenthesis group. if (lastTokenType == VARIABLE || lastTokenType == VARIABLE2 || lastTokenType == TokenType.PROPERTY) { contextParts.add(lastTokenValue); // Period is obligatory to the left of id to continue the chain. expectingPeriod = true; } else if ((lastTokenType == NULL) && (lastTokenValue.length() == 1) && SIMPLE_CONTEXT_END.contains(lastTokenValue)) { // We are to enter parenthesis group. if (!bypassParenthesizedGroup(tokens, lastToken)) { // If we were unable to properly close group - exit return expectingPeriod; } // After group is closed, we again expect id or parenthesis group. } else { // Token type we don't expect - exit return expectingPeriod; } } } return expectingPeriod; } /** * Pops tokens until context closed with lastToken is not opened, * or inconsistency found. * * @return {@code true} if context was successfully removed from tokens. */ static boolean bypassParenthesizedGroup(JsonArray<Token> tokens, Token lastToken) { JsonArray<String> stack = JsonCollections.createArray(); // Push char that corresponds to opening parenthesis. stack.add(CONTEXT_START[(CONTEXT_END.indexOf(lastToken.getValue()))]); while (!tokens.isEmpty()) { lastToken = tokens.pop(); String lastTokenValue = lastToken.getValue(); // Bypass non-parenthesis. if (lastToken.getType() != NULL || (lastTokenValue.length() != 1)) { continue; } // Dive deeper. if (CONTEXT_END.contains(lastTokenValue)) { stack.add(CONTEXT_START[(CONTEXT_END.indexOf(lastToken.getValue()))]); continue; } // Check if token corresponds to stack head if (CONTEXT_START[0].equals(lastTokenValue) || CONTEXT_START[1].equals(lastTokenValue) || CONTEXT_START[2].equals(lastTokenValue)) { if (!stack.peek().equals(lastTokenValue)) { // Got opening parenthesis not matching stack -> exit with error. return false; } stack.pop(); // If initial group is closed - we've finished. if (stack.isEmpty()) { return true; } } } return false; } /** * Types of situations. * * <p>When expanding line with letters leads to expanding last token, * it means that token is not finished. Strings and comments have such * behaviour ({@link #IN_STRING}, {@link #IN_COMMENT}). * * <p>When parse result is {@code null}, then no further analysis can be done * ({@link #NOT_PARSED}). * * <p>Otherwise (the most common and interesting situation) we suppose to be * somewhere in code ({@link #IN_CODE}). */ public enum Context { IN_STRING, IN_COMMENT, NOT_PARSED, IN_CODE } /** * Bean that wraps together {@link ParseResult} and {@link Context}. * * @param <T> language-specific {@link State} type. */ public static class ExtendedParseResult<T extends State> { private final ParseResult<T> parseResult; private final Context context; public ExtendedParseResult(ParseResult<T> parseResult, Context context) { this.parseResult = parseResult; this.context = context; } /** * @return {@code null} if parsing is failed, or token list is empty. */ public String getLastTokenValue() { if (parseResult == null) { return null; } JsonArray<Token> tokens = parseResult.getTokens(); if (tokens.isEmpty()) { return null; } Token lastToken = tokens.peek(); return lastToken.getValue(); } ParseResult<T> getParseResult() { return parseResult; } Context getContext() { return context; } } /** * Parses the line to specified position and returns parse result. * * @param parser current document parser * @param position point of interest */ public static <T extends State> ExtendedParseResult<T> getExtendedParseResult( Class<T> stateClass, @Nonnull DocumentParser parser, Position position) { int column = position.getColumn(); String text = position.getLine().getText().substring(0, column); // Add space if we are not sure that comment/literal is finished boolean addSpace = (column == 0) || text.endsWith("*/") || text.endsWith("'") || text.endsWith("\""); ParseResult<T> result = parser.getState(stateClass, position, addSpace ? SPACE : null); if (result == null) { return new ExtendedParseResult<T>(null, Context.NOT_PARSED); } JsonArray<Token> tokens = result.getTokens(); Token lastToken = tokens.peek(); Preconditions.checkNotNull(lastToken, "Last token expected to be non-null; text='%s', position=%s", text, position); TokenType lastTokenType = lastToken.getType(); String lastTokenValue = lastToken.getValue(); if (!addSpace) { if (lastTokenType == STRING || lastTokenType == REGEXP) { return new ExtendedParseResult<T>(result, Context.IN_STRING); } else if (lastTokenType == TokenType.COMMENT) { return new ExtendedParseResult<T>(result, Context.IN_COMMENT); } // Python parser, for a purpose of simplicity, parses period and variable // name as a single token. If period is not followed by identifier, parser // states that this is and error, which is, generally, not truth. if ((lastTokenType == TokenType.ERROR) && LITERAL_PERIOD.equals(lastTokenValue)) { tokens.pop(); tokens.add(new Token(lastToken.getMode(), TokenType.NULL, LITERAL_PERIOD)); } return new ExtendedParseResult<T>(result, Context.IN_CODE); } // Remove / shorten last token to omit added whitespace. tokens.pop(); if (lastTokenType == STRING || lastTokenType == REGEXP || lastTokenType == TokenType.COMMENT) { // Whitespace stuck to token - strip it. lastTokenValue = lastTokenValue.substring(0, lastTokenValue.length() - 1); tokens.add(new Token(lastToken.getMode(), lastTokenType, lastTokenValue)); if (lastTokenType == STRING || lastTokenType == REGEXP) { return new ExtendedParseResult<T>(result, Context.IN_STRING); } else { return new ExtendedParseResult<T>(result, Context.IN_COMMENT); } } // Otherwise whitespace was stated as a standalone token. return new ExtendedParseResult<T>(result, Context.IN_CODE); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/CompletionType.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CompletionType.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; /** * An enumeration of codeGraph types of autocompletions. * */ public enum CompletionType { GLOBAL, PROPERTY, 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/code/autocomplete/codegraph/ScopeTrieBuilder.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/ScopeTrieBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.AbstractTrie; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.js.JsCodeScope; import com.google.collide.client.code.autocomplete.codegraph.js.JsIndexUpdater; import com.google.collide.client.code.autocomplete.codegraph.py.PyCodeScope; import com.google.collide.client.code.autocomplete.codegraph.py.PyIndexUpdater; import com.google.collide.client.code.autocomplete.integration.TaggableLineUtil; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.client.util.logging.Log; import com.google.collide.codemirror2.State; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.dto.CodeBlock; import com.google.collide.dto.CodeBlock.Type; import com.google.collide.dto.CodeGraph; import com.google.collide.json.client.JsoStringSet; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.Position; import com.google.collide.shared.grok.GrokUtils; import com.google.collide.shared.util.JsonCollections; import com.google.common.base.Preconditions; /** * Builds a list of completion proposals from a few sources * (context file, external files and language constructs) * */ public class ScopeTrieBuilder { private static void addLexicalPrefixes( JsoStringSet prefixes, JsonArray<String> path, String commonSuffix) { for (int i = 0; i <= path.size(); i++) { String currentPrefix = (i == 0) ? "" : path.slice(0, i).join(".") + "."; prefixes.add(currentPrefix + commonSuffix); } } private static void addThisPrefixes(JsoStringSet prefixes, JsonArray<String> path) { String thisPrefix = path.slice(0, path.size() - 1).join(".") + "."; prefixes.add(thisPrefix); } private static void debugLog(CodeBlock codeBlock, String indent) { Log.debug(ScopeTrieBuilder.class, indent + CodeBlock.Type.valueOf(codeBlock.getBlockType()) + " " + codeBlock.getName() + "#" + codeBlock.getId() + "[" + codeBlock.getStartLineNumber() + ":" + codeBlock.getStartColumn() + "," + codeBlock.getEndLineNumber() + ":" + codeBlock.getEndColumn() + "]"); } private static void debugLogTree(CodeBlock root, String indent) { if (root == null) { Log.debug(ScopeTrieBuilder.class, "null code block"); return; } debugLog(root, indent); indent = " " + indent; for (int i = 0; i < root.getChildren().size(); i++) { debugLogTree(root.getChildren().get(i), indent); } } private PrefixIndex<CodeGraphProposal> externalTrie = new AbstractTrie<CodeGraphProposal>(); private final CodeFile contextFile; private final SyntaxType mode; public ScopeTrieBuilder(CodeFile contextFile, SyntaxType mode) { this.contextFile = contextFile; this.mode = mode; } public JsoStringSet calculateScopePrefixes(CompletionContext context, Position cursor) { JsoStringSet result = JsoStringSet.create(); boolean isThisContext = context.isThisContext(); Line line = cursor.getLine(); if (!isThisContext) { result.add(context.getPreviousContext()); } //PY specific. PyCodeScope pyScope = line.getTag(PyIndexUpdater.TAG_SCOPE); if (pyScope != null) { JsonArray<String> path = PyCodeScope.buildPrefix(pyScope); if (isThisContext && pyScope.getType() == PyCodeScope.Type.DEF && path.size() > 1) { addThisPrefixes(result, path); } else { addLexicalPrefixes(result, path, context.getPreviousContext()); } return result; } // Fallback - use pre-calculated results (valid at the end of line). JsCodeScope jsScope = line.getTag(JsIndexUpdater.TAG_SCOPE); @SuppressWarnings("unchecked") // Trying to get results up to cursor position. ParseResult<State> parseResult = context.getParseResult(); if (parseResult != null) { jsScope = JsIndexUpdater.calculateContext( TaggableLineUtil.getPreviousLine(line), parseResult.getTokens()).getScope(); } if (jsScope != null) { JsonArray<String> path = JsCodeScope.buildPrefix(jsScope); if (isThisContext && path.size() > 1) { addThisPrefixes(result, path); } else { addLexicalPrefixes(result, path, context.getPreviousContext()); } } int lineNumber = cursor.getLineNumber(); int column = cursor.getColumn(); column = Math.max(0, column - context.getPreviousContext().length()); final Scope scope = contextFile.findScope(lineNumber, column, true); // Can't calculate scope or matching codeBlock or it is root scope. if (scope == null || scope == contextFile.getRootScope()) { return result; } CodeBlock codeBlock = scope.getCodeBlock(); JsonArray<String> prefix = buildPrefix(codeBlock); // Add prefixes corresponding to outer scopes. if (isThisContext && Type.VALUE_FUNCTION == codeBlock.getBlockType() && prefix.size() > 1) { addThisPrefixes(result, prefix); } else { addLexicalPrefixes(result, prefix, context.getPreviousContext()); } return result; } /** * Builds sequence on names that represents path to given {@link CodeBlock}. * * <p>Given block name is the last item in resulting sequence. */ private JsonArray<String> buildPrefix(@Nonnull CodeBlock codeBlock) { Preconditions.checkNotNull(codeBlock); CodeBlock current = codeBlock; JsonArray<String> prefix = JsonCollections.createArray(); while (current != null && Type.VALUE_FILE != current.getBlockType()) { prefix.add(current.getName()); current = contextFile.getReferences().getParent(current); } prefix.reverse(); return prefix; } public void setCodeGraph(CodeGraph codeGraph) { CodeBlock contextFileCodeBlock = GrokUtils.findFileCodeBlock(codeGraph, contextFile.getFilePath().getPathString()); contextFile.setRootCodeBlock(contextFileCodeBlock); externalTrie = new CodeGraphPrefixIndex(codeGraph, mode, contextFile.getFilePath()); } public PrefixIndex<CodeGraphProposal> getCodeGraphTrie() { Preconditions.checkNotNull(externalTrie); return externalTrie; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/CompletionContext.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CompletionContext.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.codemirror2.State; /** * Data bean that represents textual context around cursor position. * * @param <T> language-specific {@link State} type. * */ public class CompletionContext<T extends State> { /** * Type of autocomplete. */ private final CompletionType completionType; /** * Flag that indicates that we are addressing object own items. */ private final boolean isThisContext; /** * Prefix (preceding expression) used for trie truncating. */ private final String previousContext; /** * Autocompleter triggering string. * * <p>String that looks like uncompleted identifier. */ private final String triggeringString; /** * Result of parsing of line to the cursor position. * * @see ParseUtils#getExtendedParseResult */ private final ParseResult<T> parseResult; /** * Proposed indention for the next line. */ private final int indent; public CompletionContext(String previousContext, String triggeringString, boolean thisContext, CompletionType completionType, ParseResult<T> parseResult, int indent) { this.previousContext = previousContext; this.triggeringString = triggeringString; this.isThisContext = thisContext; this.completionType = completionType; this.parseResult = parseResult; this.indent = indent; } public CompletionType getCompletionType() { return completionType; } public boolean isThisContext() { return isThisContext; } public String getPreviousContext() { return previousContext; } public String getTriggeringString() { return triggeringString; } public ParseResult<T> getParseResult() { return parseResult; } public int getIndent() { return indent; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/CodeFile.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/CodeFile.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import static com.google.collide.shared.document.util.LineUtils.comparePositions; import java.util.HashMap; import java.util.Map; import com.google.collide.client.util.PathUtil; import com.google.collide.dto.CodeBlock; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.util.LineUtils; import com.google.collide.shared.util.JsonCollections; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * Encapsulates code structure data of the file opened in the editor. * */ class CodeFile { static class CodeBlockReferences { private final Map<CodeBlock, CodeBlock> childParentRefs = new HashMap<CodeBlock, CodeBlock>(); void addChildParentRef(CodeBlock child, CodeBlock parent) { childParentRefs.put(child, parent); } CodeBlock getParent(CodeBlock child) { return childParentRefs.get(child); } void clear() { childParentRefs.clear(); } } private static Scope findScope(Scope scope, int lineNumber, int column, boolean endInclusive) { int relativeToBegin = comparePositions(lineNumber, column, scope.getBeginLineNumber(), scope.getBeginColumn()); // When we say that cursor column is X, we mean, that there are X chars // before cursor in this line. // But when we say that scope ends at column X, we mean that X-th char is // the last char that belongs to the scope. // That is why we do +1 to make this function work as designed. int scopeEndColumn = scope.getEndColumn() + 1; int relativeToEnd = comparePositions(lineNumber, column, scope.getEndLineNumber(), scopeEndColumn); if (relativeToBegin < 0 || relativeToEnd > 0) { return null; } if (!endInclusive && relativeToEnd == 0) { return null; } for (int i = 0; i < scope.getSubscopes().size(); ++i) { Scope subScope = findScope(scope.getSubscopes().get(i), lineNumber, column, endInclusive); if (subScope != null) { return subScope; } } return scope; } private final CodeBlockReferences refs = new CodeBlockReferences(); private final PathUtil filePath; private CodeBlock rootCodeBlock; private Scope rootScope; CodeFile(PathUtil filePath) { Preconditions.checkNotNull(filePath); this.filePath = filePath; } private void buildSubscopes(Scope rootScope, CodeBlock codeBlock, JsonArray<CodeBlock> queue) { JsonArray<Scope> subscopes = rootScope.getSubscopes(); for (int i = 0, size = codeBlock.getChildren().size(); i < size; i++) { CodeBlock child = codeBlock.getChildren().get(i); refs.addChildParentRef(child, codeBlock); if (isTextuallyNested(child, codeBlock)) { Scope childScope = new Scope(child); subscopes.add(childScope); } else { queue.add(child); } } for (int i = 0; i < subscopes.size(); i++) { Scope child = subscopes.get(i); buildSubscopes(child, child.getCodeBlock(), queue); } } private boolean isTextuallyNested(CodeBlock child, CodeBlock parent) { return LineUtils.comparePositions(child.getStartLineNumber(), child.getStartColumn(), parent.getStartLineNumber(), parent.getStartColumn()) >= 0 && LineUtils.comparePositions(child.getEndLineNumber(), child.getEndColumn(), parent.getEndLineNumber(), parent.getEndColumn()) <= 0; } /** * Finds the most suitable scope for a given position. * * @param lineNumber position line number * @param column position column * @param endInclusive when {@code true} then scopes are suitable if they * can be expanded by adding something at the given position * @return scope found */ Scope findScope(int lineNumber, int column, boolean endInclusive) { if (rootScope == null) { return null; } return findScope(rootScope, lineNumber, column, endInclusive); } PathUtil getFilePath() { return filePath; } CodeBlockReferences getReferences() { return refs; } CodeBlock getRootCodeBlock() { return rootCodeBlock; } @VisibleForTesting Scope getRootScope() { return this.rootScope; } void setRootCodeBlock(CodeBlock codeBlock) { this.rootCodeBlock = codeBlock; if (codeBlock == null) { return; } refs.clear(); rootScope = new Scope(codeBlock); JsonArray<CodeBlock> queue = JsonCollections.createArray(); buildSubscopes(rootScope, rootCodeBlock, queue); while (!queue.isEmpty()) { JsonArray<CodeBlock> newQueue = JsonCollections.createArray(); for (int i = 0; i < queue.size(); i++) { CodeBlock queued = queue.get(i); Scope lexicalContainer = findScope(queued.getStartLineNumber(), queued.getStartColumn(), false); if (lexicalContainer != null) { Scope lexicalScope = new Scope(queued); lexicalContainer.getSubscopes().add(lexicalScope); buildSubscopes(lexicalScope, queued, newQueue); } } queue = newQueue; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/ProposalBuilder.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/ProposalBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph; import static com.google.collide.client.code.autocomplete.codegraph.ParseUtils.Context.IN_CODE; import static com.google.collide.codemirror2.Token.LITERAL_PERIOD; import static com.google.collide.codemirror2.TokenType.KEYWORD; import static com.google.collide.codemirror2.TokenType.NULL; import static com.google.collide.codemirror2.TokenType.VARIABLE; import static com.google.collide.codemirror2.TokenType.VARIABLE2; import static com.google.collide.codemirror2.TokenType.WHITESPACE; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.code.autocomplete.AutocompleteProposals.Context; import com.google.collide.client.code.autocomplete.AutocompleteResult; import com.google.collide.client.code.autocomplete.Autocompleter; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.ParseUtils.ExtendedParseResult; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.PathUtil; import com.google.collide.codemirror2.State; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.client.JsoStringSet; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.document.Position; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; // TODO: Implement autocompletion-session end notification. /** * Builds CompletionContext and proposals list. * * @param <T> language-specific {@link State} type. */ public abstract class ProposalBuilder<T extends State> { // TODO: Fix wording. private static final String HINT = "Press Ctrl-Shift-Space for alternate completion"; private final Class<T> stateClass; protected ProposalBuilder(Class<T> stateClass) { this.stateClass = stateClass; } /** * Add more proposals prefixes based on language specifics. */ protected abstract void addShortcutsTo(CompletionContext<T> context, JsonStringSet prefixes); /** * Returns language-specific templates. * * <p>Only lower-case items will match in case-insensitive mode. */ protected abstract PrefixIndex<TemplateProposal> getTemplatesIndex(); /** * Returns local variables visible in the current scope. */ protected abstract JsonArray<String> getLocalVariables(ParseResult<T> parseResult); /** * Checks if the given prefix denotes "this"/"self" context. * * <p>Prefix is the beginning of the statement to the last period (including). * * <p>In case implementation returns {@code true} - * {@link CompletionContext#previousContext} is turned to empty in a purpose * of shortcutting. * * TODO: I think we should move this implicit shortcutting to a more * proper place. */ protected abstract boolean checkIsThisPrefix(String prefix); /** * Constructs context based on text around current cursor position. */ @VisibleForTesting public CompletionContext<T> buildContext( SelectionModel selection, @Nonnull DocumentParser parser) { ExtendedParseResult<T> parseResult = ParseUtils.getExtendedParseResult( stateClass, parser, selection.getCursorPosition()); if (parseResult.getContext() != IN_CODE) { return null; } return buildContext(parseResult); } protected CompletionContext<T> buildContext(ExtendedParseResult<T> extendedParseResult) { Preconditions.checkArgument(extendedParseResult.getContext() == IN_CODE); ParseResult<T> parseResult = extendedParseResult.getParseResult(); JsonArray<Token> tokens = parseResult.getTokens(); if (tokens.isEmpty()) { return new CompletionContext<T>("", "", false, CompletionType.GLOBAL, parseResult, 0); } int indent = 0; if (TokenType.WHITESPACE == tokens.get(0).getType()) { indent = tokens.get(0).getValue().length(); } Token lastToken = tokens.pop(); TokenType lastTokenType = lastToken.getType(); if (lastTokenType == WHITESPACE) { return new CompletionContext<T>("", "", false, CompletionType.GLOBAL, parseResult, indent); } String lastTokenValue = lastToken.getValue(); if (lastTokenType == KEYWORD) { return new CompletionContext<T>( "", lastTokenValue, false, CompletionType.GLOBAL, parseResult, indent); } boolean expectingPeriod = true; String triggeringString; // Property autocompletion only when cursor stands after period or id. if (lastTokenType == VARIABLE || lastTokenType == VARIABLE2 || lastTokenType == TokenType.PROPERTY) { triggeringString = lastTokenValue; } else if ((lastTokenType == NULL) && LITERAL_PERIOD.equals(lastTokenValue)) { triggeringString = ""; expectingPeriod = false; } else { return new CompletionContext<T>("", "", false, CompletionType.GLOBAL, parseResult, indent); } JsonArray<String> contextParts = JsonCollections.createArray(); expectingPeriod = ParseUtils .buildInvocationSequenceContext(tokens, expectingPeriod, contextParts); contextParts.reverse(); // If there were no more ids. if (contextParts.isEmpty() && expectingPeriod) { return new CompletionContext<T>( "", triggeringString, false, CompletionType.GLOBAL, parseResult, indent); } // TODO: What if expectingPeriod == false? String previousContext = contextParts.join(".") + "."; boolean isThisContext = checkIsThisPrefix(previousContext); return new CompletionContext<T>(previousContext, triggeringString, isThisContext, CompletionType.PROPERTY, parseResult, indent); } // TODO: Implement multiline context building. /** * Build {@link AutocompleteResult} according to current context and * selected proposal. */ AutocompleteResult computeAutocompletionResult( CodeGraphProposal selectedProposal, String triggeringString) { String name = selectedProposal.getName(); int tailOffset = 0; if (selectedProposal.isFunction()) { tailOffset = 1; name += "()"; } return new DefaultAutocompleteResult(name, triggeringString, name.length() - tailOffset); } public AutocompleteProposals getProposals(SyntaxType mode, @Nonnull DocumentParser parser, SelectionModel selection, ScopeTrieBuilder scopeTrieBuilder) { CompletionContext<T> context = buildContext(selection, parser); if (context == null) { return AutocompleteProposals.EMPTY; } String triggeringString = context.getTriggeringString(); JsonArray<AutocompleteProposal> items = doGetProposals( context, selection.getCursorPosition(), scopeTrieBuilder); return new AutocompleteProposals( mode, new Context(triggeringString, context.getIndent()), items, HINT); } @VisibleForTesting JsonArray<AutocompleteProposal> doGetProposals( CompletionContext<T> context, Position cursorPosition, ScopeTrieBuilder scopeTrieBuilder) { String itemPrefix = context.getTriggeringString(); boolean ignoreCase = Autocompleter.CASE_INSENSITIVE; if (ignoreCase) { itemPrefix = itemPrefix.toLowerCase(); } // A set used to avoid duplicates. JsoStringSet uniqueNames = JsoStringSet.create(); // This array will be filled with proposals form different sources: // templates; visible names found by parser; matches from code graph. JsonArray<AutocompleteProposal> result = JsonCollections.createArray(); // This also means previousContext == "" if (CompletionType.GLOBAL == context.getCompletionType()) { // Add templates. JsonArray<? extends TemplateProposal> templates = getTemplatesIndex().search(itemPrefix); result.addAll(templates); for (TemplateProposal template : templates.asIterable()) { uniqueNames.add(template.getName()); } // Add visible names found by parser. JsonArray<String> localVariables = getLocalVariables(context.getParseResult()); for (String localVariable : localVariables.asIterable()) { if (StringUtils.startsWith(itemPrefix, localVariable, ignoreCase)) { if (!uniqueNames.contains(localVariable)) { uniqueNames.add(localVariable); result.add(new CodeGraphProposal(localVariable, PathUtil.EMPTY_PATH, false)); } } } } // Now use the knowledge about current scope and calculate possible // shortcuts in code graph. JsonStringSet prefixes = scopeTrieBuilder.calculateScopePrefixes(context, cursorPosition); // Let language-specific modifications. addShortcutsTo(context, prefixes); PrefixIndex<CodeGraphProposal> codeGraphTrie = scopeTrieBuilder.getCodeGraphTrie(); JsonArray<AutocompleteProposal> codeProposals = JsonCollections.createArray(); // We're iterate found shortcuts... for (String prefix : prefixes.getKeys().asIterable()) { JsonArray<? extends CodeGraphProposal> proposals = codeGraphTrie.search(prefix + itemPrefix); // Distill raw proposals. int prefixLength = prefix.length(); for (CodeGraphProposal proposal : proposals.asIterable()) { // Take part of string between prefix and period. String proposalName = proposal.getName(); int nameEndIndex = proposalName.length(); int periodIndex = proposalName.indexOf('.', prefixLength); if (periodIndex != -1) { // TODO: Do we need this? nameEndIndex = periodIndex; } proposalName = proposalName.substring(prefixLength, nameEndIndex); if (!uniqueNames.contains(proposalName)) { uniqueNames.add(proposalName); codeProposals.add( new CodeGraphProposal(proposalName, proposal.getPath(), proposal.isFunction())); } } } result.addAll(codeProposals); 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/code/autocomplete/codegraph/py/PyAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/py/PyAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.py; import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.ExplicitAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.LimitedContextFilePrefixIndex; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.codemirror2.SyntaxType; /** * Constructor of instance of {@link CodeGraphAutocompleter} * configured for Python autocompletion. */ public class PyAutocompleter { /** * Construct instance of Python autocompleter. * * @return configured instance of Python autocompleter */ public static CodeGraphAutocompleter create( CubeClient cubeClient, LimitedContextFilePrefixIndex contextFilePrefixIndex) { return new CodeGraphAutocompleter( SyntaxType.PY, new PyProposalBuilder(), cubeClient, contextFilePrefixIndex, new ExplicitAutocompleter()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/py/PyConstants.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/py/PyConstants.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.py; import com.google.collide.client.code.autocomplete.AbstractTrie; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.TemplateProposal; /** * Singleton that holds various PY-specific constants. */ class PyConstants { private static PyConstants instance; /** * @return the singleton instance of this class. */ static PyConstants getInstance() { if (instance == null) { instance = new PyConstants(); } return instance; } private static void addProposal(AbstractTrie<TemplateProposal> to, String name, String template) { to.put(name, new TemplateProposal(name, template)); } private final PrefixIndex<TemplateProposal> templatesTrie; private PyConstants() { AbstractTrie<TemplateProposal> temp = new AbstractTrie<TemplateProposal>(); addProposal(temp, "and", "and "); addProposal(temp, "assert", "assert "); addProposal(temp, "break", "break%d"); addProposal(temp, "class", "class %c:%i\"\""); addProposal(temp, "continue", "continue%d"); addProposal(temp, "def", "def "); addProposal(temp, "del", "del "); // TODO: Reindent current line. addProposal(temp, "elif", "elif "); // TODO: Reindent current line. addProposal(temp, "else", "else%i"); // TODO: Reindent current line. addProposal(temp, "except", "except %c:%i"); addProposal(temp, "exec", "exec "); // TODO: Reindent current line. addProposal(temp, "finally", "finally:%i"); addProposal(temp, "for", "for %c in :"); addProposal(temp, "from", "from %c import "); addProposal(temp, "global", "global "); addProposal(temp, "if", "if %c:"); addProposal(temp, "import", "import "); addProposal(temp, "in", "in "); addProposal(temp, "is", "is "); addProposal(temp, "lambda", "lambda %c: "); addProposal(temp, "not", "not "); addProposal(temp, "or", "or "); addProposal(temp, "pass", "pass%d"); addProposal(temp, "print", "print "); addProposal(temp, "raise", "raise "); addProposal(temp, "return", "return "); addProposal(temp, "try", "try:%i"); addProposal(temp, "with", "with "); addProposal(temp, "while", "while %c:%i"); addProposal(temp, "yield", "yield "); templatesTrie = temp; } PrefixIndex<TemplateProposal> getTemplatesTrie() { return templatesTrie; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/py/PyIndexUpdater.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/py/PyIndexUpdater.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.py; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.CodeAnalyzer; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; /** * Python specific code analyzer. * * <p>This class calculates scope for each line of code. */ public class PyIndexUpdater implements CodeAnalyzer { public static final String TAG_SCOPE = PyIndexUpdater.class.getName() + ".scope"; /** * Python keyword for function definition. */ private static final String LITERAL_DEF = "def"; /** * Python keyword for class definition. */ private static final String LITERAL_CLASS = "class"; @Override public void onBeforeParse() { } @Override public void onParseLine( TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens) { PyCodeScope prevScope = previousLine.getTag(TAG_SCOPE); PyCodeScope scope = prevScope; int indent = 0; int n = tokens.size(); int i = 0; if (n > 0) { Token token = tokens.get(i); if (TokenType.WHITESPACE == token.getType()) { i++; indent = token.getValue().length(); } if (n >= i + 3 && TokenType.KEYWORD == tokens.get(i).getType() && TokenType.WHITESPACE == tokens.get(i + 1).getType() && TokenType.VARIABLE == tokens.get(i + 2).getType()) { String keyword = tokens.get(i).getValue(); boolean isClass = LITERAL_CLASS.equals(keyword); boolean isDef = LITERAL_DEF.equals(keyword); if (isClass || isDef) { while (prevScope != null) { if (prevScope.getIndent() < indent) { break; } prevScope = prevScope.getParent(); } PyCodeScope.Type type = isDef ? PyCodeScope.Type.DEF : PyCodeScope.Type.CLASS; scope = new PyCodeScope(prevScope, tokens.get(i + 2).getValue(), indent, type); } } } line.putTag(TAG_SCOPE, scope); } @Override public void onAfterParse() { } @Override public void onLinesDeleted(JsonArray<TaggableLine> deletedLines) { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/py/PyParsingTask.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/py/PyParsingTask.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.py; import static com.google.collide.codemirror2.TokenType.KEYWORD; import static com.google.collide.codemirror2.TokenType.VARIABLE; import static com.google.collide.codemirror2.TokenType.WHITESPACE; import com.google.collide.client.code.autocomplete.codegraph.Position; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * Python specific parsing task. * * <p>This class recognizes variables and function names in stream of tokens. * */ @Deprecated class PyParsingTask /*extends ParsingTask*/ { /** * Delimiter that starts new code block. */ private static final String LITERAL_COLON = ":"; /** * Delimiter that starts parameters definition when encountered in * function definition. */ private static final String LITERAL_LEFT_PARANTHESIS = "("; /** * Delimiter that can separate multiple variables in lvalue. */ private static final String LITERAL_COMMA = ","; /** * Assignment operator token. */ private static final String LITERAL_EQUALS = "="; /** * Runs one-line parsing iteration. During parsing it fills the result scope * with identifiers. */ // @Override protected void processLine(int lineNumber, JsonArray<Token> tokens) { PyParseContext context = new PyParseContext(); // TODO: should either remove column information from system // or add column information to tokens int fakeTokenColumn = 0; // Last token in always newline, see DocumentParserWorker. final int l = tokens.size() - 1; for (int i = 0; i < l; i++) { Token token = tokens.get(i); assert token != null; // Ignore whitespaces if (WHITESPACE == token.getType()) { continue; } // Common precondition: context is not too short if (context.predPred == null) { context.push(token); continue; } PyToken predPred = context.predPred; PyToken pred = context.pred; // In case we get ":" or "(" it may be a function definition if (LITERAL_COLON.equals(token.getValue()) || LITERAL_LEFT_PARANTHESIS.equals(token.getValue())) { if ((KEYWORD == predPred.getType()) && "def".equals(predPred.getContent())) { // getResultScope().addToken(lineNumber, fakeTokenColumn, // new CodeToken(pred.getContent(), pred.getType(), true)); } fakeTokenColumn++; context.push(token); continue; } // When we get ", id," construction, // then do not reset accumulator (ids before first comma) if (LITERAL_COMMA.equals(token.getValue())) { if (LITERAL_COMMA.equals(predPred.getContent())) { if (VARIABLE == pred.getType()) { context.pushSavingAccumulator(token); continue; } } context.push(token); continue; } // When we got "id =" then register all remembered ids as variables if (LITERAL_EQUALS.equals(token.getValue())) { if (VARIABLE == context.pred.getType()) { context.accumulator.add(context.pred); while (!context.accumulator.isEmpty()) { PyToken nextVar = context.accumulator.pop(); // getResultScope().addToken(lineNumber, fakeTokenColumn, // new CodeToken(nextVar.getContent(), nextVar.getType())); fakeTokenColumn++; } } context.push(token); continue; } // When we get "id1, id2" construction // then remember id1, because it is going to be pushed out of context. if (VARIABLE == token.getType()) { if (VARIABLE == context.predPred.getType()) { if (LITERAL_COMMA.equals(context.pred.getContent())) { context.pushAndAddToAccumulator(token); continue; } } context.push(token); continue; } context.push(token); } context.push(tokens.get(l)); } /** * Context that holds a number of previous tokens. * * <p>Some tokens are saved to accumulator. Usually accumulator holds * identifier-tokens within the same context. */ private class PyParseContext { PyToken pred = null; PyToken predPred = null; final JsonArray<PyToken> accumulator = JsonCollections.createArray(); void push(Token token) { accumulator.clear(); pushSavingAccumulator(token); } void pushAndAddToAccumulator(Token token) { accumulator.add(predPred); pushSavingAccumulator(token); } void pushSavingAccumulator(Token token) { predPred = pred; pred = new PyToken(token, 0, 0); } } /** * Immutable combination of token and position. * * <p>Dispatches common messages to token. */ private static class PyToken { final Token token; final Position position; PyToken(Token token, int lineNumber, int column) { this.token = token; this.position = Position.from(lineNumber, column); } String getContent() { return token.getValue(); } public TokenType getType() { return token.getType(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/py/PyCodeScope.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/py/PyCodeScope.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.py; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * Class that defines the PY code scope calculated during parsing. * * <p>This instance holds the reference to parent, so for any line of code we * can store a single item; at the same time, many items can share a parent. */ public class PyCodeScope { /** * Enumeration of scope types. */ public enum Type { CLASS, DEF } /** * Indention of the line with definition. */ private final int indent; /** * Enum that specifies the type of scope. */ private final Type type; /** * Name of the scope. */ private final String name; /** * Parent scope. * * <p>{@code null} means that this scope is one of the root scopes. */ private final PyCodeScope parent; /** * Constructs the bean. */ public PyCodeScope(PyCodeScope parent, String name, int indent, Type type) { this.parent = parent; this.name = name; this.indent = indent; this.type = type; } /** * Builds the trie prefix for specified scope. * * <p>In result the root scope goes first, the innermost (the given one) is * represented at last position. */ public static JsonArray<String> buildPrefix(PyCodeScope scope) { JsonArray<String> result = JsonCollections.createArray(); while (scope != null) { result.add(scope.getName()); scope = scope.getParent(); } result.reverse(); return result; } public int getIndent() { return indent; } public Type getType() { return type; } public String getName() { return name; } public PyCodeScope getParent() { return parent; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/py/PyProposalBuilder.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/py/PyProposalBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.py; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.CompletionContext; import com.google.collide.client.code.autocomplete.codegraph.ProposalBuilder; import com.google.collide.client.code.autocomplete.codegraph.TemplateProposal; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.codemirror2.PyState; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.util.JsonCollections; import com.google.common.annotations.VisibleForTesting; /** * PY specific {@link ProposalBuilder} implementation. * */ @VisibleForTesting public class PyProposalBuilder extends ProposalBuilder<PyState> { public PyProposalBuilder() { super(PyState.class); } @Override protected PrefixIndex<TemplateProposal> getTemplatesIndex() { return PyConstants.getInstance().getTemplatesTrie(); } @Override protected void addShortcutsTo(CompletionContext<PyState> context, JsonStringSet prefixes) { } @Override protected JsonArray<String> getLocalVariables(ParseResult<PyState> pyStateParseResult) { return JsonCollections.createArray(); } @Override protected boolean checkIsThisPrefix(String prefix) { return "self.".equals(prefix); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/js/JsIndexUpdater.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsIndexUpdater.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.CodeAnalyzer; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; /** * JavaScript specific code analyzer. * * <p>This class calculates scope for each line of code. */ public class JsIndexUpdater implements CodeAnalyzer { public static final String TAG_SCOPE = JsIndexUpdater.class.getName() + ".scope"; private static final String TAG_STATE = JsIndexUpdater.class.getName() + ".state"; /** * Tag for storing incomplete scope name. */ private static final String TAG_NAME = JsIndexUpdater.class.getName() + ".sName"; private static final String LITERAL_FUNCTION = "function"; private static final String LITERAL_PERIOD = "."; private static final String LITERAL_ASSIGN = "="; private static final String LITERAL_COLON = ":"; private static final String LITERAL_OPEN_BRACKET = "("; private static final String LITERAL_CLOSE_BRACKET = ")"; private static final String LITERAL_COMMA = ","; private static final String LITERAL_OPEN_CURLY = "{"; private static final String LITERAL_CLOSE_CURLY = "}"; /** * Checks if the token describes some name (variable, function) or * name part (property). */ private static boolean isName(TokenType type) { return TokenType.VARIABLE == type || TokenType.VARIABLE2 == type || TokenType.DEF == type || TokenType.PROPERTY == type; } private static boolean isFunctionKeyword(TokenType tokenType, String tokenValue) { return TokenType.KEYWORD == tokenType && LITERAL_FUNCTION.equals(tokenValue); } /** * Enumeration of situations that may occur during scope parsing. */ private enum State { /** * Without particular context. */ NONE, /** * Keyword "function" met, expecting name. */ FUNCTION, /** * Context with intention to define named function. * * <p>Expecting "(" */ NAMED_FUNCTION, /** * Inside params definition. */ FUNCTION_PARAMS, /** * Function name and params are known, expecting block start. */ FULLY_QUALIFIED, /** * (Variable) name met. Expecting "=", ":", or "." */ NAME, /** * Got something like "name1.", expecting next name. */ SUBNAME, /** * Got something like "name1.name2 =", or "name1:". * * <p>Expecting "function" keyword. */ ASSIGN, } /** * Bean that holds line-parsing context. */ public static class Context { private final State state; private final String name; private final JsCodeScope scope; /** * Constructs context from saved values. */ public Context(TaggableLine line) { scope = line.getTag(TAG_SCOPE); name = line.getTag(TAG_NAME); State tempState = line.getTag(TAG_STATE); if (tempState == null) { tempState = State.NONE; } state = tempState; } private Context(State state, String name, JsCodeScope scope) { this.state = state; this.name = name; this.scope = scope; } private void saveToLine(TaggableLine line) { line.putTag(TAG_SCOPE, scope); line.putTag(TAG_NAME, name); line.putTag(TAG_STATE, state); } public JsCodeScope getScope() { return scope; } } /** * Calculates updated context based on previous line context and tokens. * * <p>Note: currently we do not create root scope, so {@code null} scope * corresponds to root. */ public static Context calculateContext(TaggableLine previousLine, JsonArray<Token> tokens) { Context context = new Context(previousLine); State state = context.state; String name = context.name; JsCodeScope scope = context.scope; int size = tokens.size(); int index = 0; while (index < size) { Token token = tokens.get(index); index++; TokenType tokenType = token.getType(); if (TokenType.WHITESPACE == tokenType || TokenType.NEWLINE == tokenType || TokenType.COMMENT == tokenType) { // TODO: Parse JsDocs. continue; } String tokenValue = token.getValue(); switch (state) { case NONE: if (isFunctionKeyword(tokenType, tokenValue)) { state = State.FUNCTION; } else if (isName(tokenType)) { name = tokenValue; state = State.NAME; } else if (LITERAL_OPEN_CURLY.equals(tokenValue)) { scope = new JsCodeScope(scope, null); name = null; } else if (LITERAL_CLOSE_CURLY.equals(tokenValue)) { if (scope != null) { scope = scope.getParent(); } } break; case FUNCTION: if (isName(tokenType)) { name = tokenValue; state = State.NAMED_FUNCTION; } else { index--; name = null; state = State.NONE; } break; case NAMED_FUNCTION: if (LITERAL_OPEN_BRACKET.equals(tokenValue)) { state = State.FUNCTION_PARAMS; } else { index--; name = null; state = State.NONE; } break; case FUNCTION_PARAMS: if (LITERAL_CLOSE_BRACKET.equals(tokenValue)) { state = State.FULLY_QUALIFIED; } else if (isName(tokenType) || LITERAL_COMMA.equals(tokenValue)) { // Do nothing. } else { index--; name = null; state = State.NONE; } break; case FULLY_QUALIFIED: if (LITERAL_OPEN_CURLY.equals(tokenValue)) { scope = new JsCodeScope(scope, name); name = null; state = State.NONE; } else { index--; name = null; state = State.NONE; } break; case NAME: if (LITERAL_PERIOD.equals(tokenValue)) { state = State.SUBNAME; } else if (LITERAL_ASSIGN.equals(tokenValue) || LITERAL_COLON.equals(tokenValue)) { state = State.ASSIGN; } else { index--; name = null; state = State.NONE; } break; case SUBNAME: if (isName(tokenType)) { name = name + "." + tokenValue; state = State.NAME; } else { index--; name = null; state = State.NONE; } break; case ASSIGN: if (isFunctionKeyword(tokenType, tokenValue)) { state = State.NAMED_FUNCTION; } else if (LITERAL_OPEN_CURLY.equals(tokenValue)) { scope = new JsCodeScope(scope, name); name = null; state = State.NONE; } else { index--; name = null; state = State.NONE; } break; default: throw new IllegalStateException("Unexpected state [" + state + "]"); } } return new Context(state, name, scope); } @Override public void onBeforeParse() { } @Override public void onParseLine( TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens) { calculateContext(previousLine, tokens).saveToLine(line); } @Override public void onAfterParse() { } @Override public void onLinesDeleted(JsonArray<TaggableLine> deletedLines) { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/js/JsAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.LimitedContextFilePrefixIndex; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.codemirror2.SyntaxType; /** * Constructor of instance of {@link CodeGraphAutocompleter} * configured for JavaScript autocompletion. */ public class JsAutocompleter { /** * Construct instance of JavaScript autocompleter. * * @return configured instance of JavaScript autocompleter */ public static CodeGraphAutocompleter create( CubeClient cubeClient, LimitedContextFilePrefixIndex contextFilePrefixIndex) { return new CodeGraphAutocompleter( SyntaxType.JS, new JsProposalBuilder(), cubeClient, contextFilePrefixIndex, new JsExplicitAutocompleter()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/js/JsCodeScope.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsCodeScope.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; /** * Class that defines the JS code scope calculated during parsing. * * <p>This instance holds the reference to parent, so for any line of code we * can store a single item; at the same time, many items can share a parent. * */ public class JsCodeScope { /** * Builds the trie prefix for specified scope. * * <p>In result the root scope goes first, the innermost (the given one) is * represented at last position. */ public static JsonArray<String> buildPrefix(JsCodeScope scope) { JsonArray<String> result = JsonCollections.createArray(); while (scope != null) { String scopeName = scope.getName(); if (scopeName != null) { JsonArray<String> parts = StringUtils.split(scopeName, "."); parts.reverse(); result.addAll(parts); } scope = scope.getParent(); } result.reverse(); return result; } /** * Parent scope. * * <p>{@code null} means that this scope is one of the root scopes. */ private final JsCodeScope parent; private final String name; public JsCodeScope(JsCodeScope parent, String name) { this.parent = parent; this.name = name; } public JsCodeScope getParent() { return parent; } public String getName() { return name; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsParsingTask.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsParsingTask.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import static com.google.collide.codemirror2.TokenType.DEF; import static com.google.collide.codemirror2.TokenType.KEYWORD; import static com.google.collide.codemirror2.TokenType.NEWLINE; import static com.google.collide.codemirror2.TokenType.VARIABLE; import static com.google.collide.codemirror2.TokenType.VARIABLE2; import static com.google.collide.codemirror2.TokenType.WHITESPACE; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; /** * JavaScript specific parsing task. * * <p>This class recognizes variables and function names in stream of tokens. */ @Deprecated class JsParsingTask /*extends ParsingTask*/ { private static final String LITERAL_FUNCTION = "function"; private static boolean isVariable(TokenType type) { return VARIABLE == type || VARIABLE2 == type || DEF == type; } /** * Parsing context stores 2 previous tokens to make it possible to find some * of the cases when a token is recognized as a function. * * Tries to understand the following sequences of tokens to extract * function names: <ul> * <li>function <i>id</i></li> * <li><i>id</i> : function </li> * <li><i>id</i> = function </li> * <li><i>id</i>(</li> * </ul> */ private static class JsParsingContext { private static final String COLON_OPERATOR = ":"; private static final String EQUALS_OPERATOR = "="; private static final String LEFT_PAR = "("; private Token pred = null; private Token predpred = null; /** * Finds cases when a token might be recognized as a function. * * <p>nextToken is not pushed to the context, but used for analysis. * That way we have 3 sequential tokens to analyse: * {@code predPred, pred, nextToken}. * * @param nextToken a token that is going to be pushed to context * @return a token that might be a function or {@code null} if there is * no sign of a function */ Token getFunctionToken(Token nextToken) { if (pred == null) { return null; } if (KEYWORD == pred.getType() && LITERAL_FUNCTION.equals(pred.getValue())) { return nextToken; } if (LEFT_PAR.equals(nextToken.getValue()) && isVariable(pred.getType())) { return pred; } if (KEYWORD == nextToken.getType() && LITERAL_FUNCTION.equals(nextToken.getValue()) && predpred != null && isVariable(predpred.getType()) && (COLON_OPERATOR.equals(pred.getValue()) || EQUALS_OPERATOR.equals(pred.getValue()))) { return predpred; } return null; } /** * Consumes next token. * * <p>Tokens that hold no information are omitted. * * @param nextToken token to push to context */ private void nextToken(Token nextToken) { TokenType nextTokenType = nextToken.getType(); if (WHITESPACE != nextTokenType && NEWLINE != nextTokenType) { predpred = pred; pred = nextToken; } } } // @Override protected void processLine(int lineNumber, JsonArray<Token> tokens) { JsParsingContext context = new JsParsingContext(); for (int i = 0; i < tokens.size(); i++) { Token token = tokens.get(i); if (isVariable(token.getType())) { // getResultScope().addToken( // lineNumber, 0, new CodeToken(token.getValue().trim(), token.getType())); } Token functionToken = context.getFunctionToken(token); if (functionToken != null) { // getResultScope().addToken(lineNumber, 0, // new CodeToken(functionToken.getValue().trim(), functionToken.getType(), true)); } context.nextToken(token); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/js/JsProposalBuilder.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsProposalBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.CompletionContext; import com.google.collide.client.code.autocomplete.codegraph.ProposalBuilder; import com.google.collide.client.code.autocomplete.codegraph.TemplateProposal; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.codemirror2.JsLocalVariable; import com.google.collide.codemirror2.JsState; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.util.JsonCollections; /** * JS specific {@link ProposalBuilder} implementation. * */ class JsProposalBuilder extends ProposalBuilder<JsState> { static final String WINDOW_PREFIX = "window."; JsProposalBuilder() { super(JsState.class); } @Override protected PrefixIndex<TemplateProposal> getTemplatesIndex() { return JsConstants.getInstance().getTemplatesTrie(); } @Override protected void addShortcutsTo(CompletionContext<JsState> context, JsonStringSet prefixes) { if (!context.isThisContext()) { String previousContext = context.getPreviousContext(); if (!previousContext.startsWith(WINDOW_PREFIX)) { prefixes.add(WINDOW_PREFIX + previousContext); } } } @Override protected boolean checkIsThisPrefix(String prefix) { return "this.".equals(prefix); } protected JsonArray<String> getLocalVariables(ParseResult<JsState> parseResult) { if (parseResult == null) { return JsonCollections.createArray(); } JsonArray<String> result = JsonCollections.createArray(); JsState jsState = parseResult.getState(); JsLocalVariable localVariable = jsState.getLocalVariables(); while (localVariable != null) { result.add(localVariable.getName()); localVariable = localVariable.getNext(); } 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/code/autocomplete/codegraph/js/JsConstants.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsConstants.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import com.google.collide.client.code.autocomplete.AbstractTrie; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.TemplateProposal; /** * Singleton that holds various JS-specific constants. */ class JsConstants { private static JsConstants instance; /** * @return the singleton instance of this class. */ static JsConstants getInstance() { if (instance == null) { instance = new JsConstants(); } return instance; } private static void addProposal(AbstractTrie<TemplateProposal> to, String name, String template) { to.put(name, new TemplateProposal(name, template)); } private final PrefixIndex<TemplateProposal> templatesTrie; private JsConstants() { AbstractTrie<TemplateProposal> temp = new AbstractTrie<TemplateProposal>(); addProposal(temp, "break", "break"); addProposal(temp, "case", "case %c:"); addProposal(temp, "continue", "continue"); addProposal(temp, "default", "default: "); addProposal(temp, "delete", "delete "); addProposal(temp, "do", "do {%i%c%n} while ()"); addProposal(temp, "else", "else {%n%c%n}"); addProposal(temp, "export", "export "); addProposal(temp, "for", "for (%c;;) {%i%n}"); addProposal(temp, "function", "function %c() {%i%n}"); addProposal(temp, "if", "if (%c) {%i%n}"); addProposal(temp, "import", "import "); addProposal(temp, "in", "in "); addProposal(temp, "label", "label "); addProposal(temp, "new", "new "); addProposal(temp, "return", "return"); addProposal(temp, "switch", "switch (%c) {%i%n}"); addProposal(temp, "this", "this"); addProposal(temp, "typeof", "typeof"); addProposal(temp, "var", "var "); addProposal(temp, "void", "void "); addProposal(temp, "while", "while (%c) {%i%n}"); addProposal(temp, "with", "with "); templatesTrie = temp; } PrefixIndex<TemplateProposal> getTemplatesTrie() { return templatesTrie; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/js/JsExplicitAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/js/JsExplicitAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.js; import javax.annotation.Nonnull; import org.waveprotocol.wave.client.common.util.SignalEvent.KeySignalType; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter.ExplicitAction; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.code.autocomplete.codegraph.ExplicitAutocompleter; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.shared.document.anchor.ReadOnlyAnchor; import com.google.collide.shared.util.StringUtils; import com.google.gwt.event.dom.client.KeyCodes; /** * Implementation that adds JS-specific cases. */ class JsExplicitAutocompleter extends ExplicitAutocompleter { @Override protected ExplicitAction getExplicitAction(SelectionModel selectionModel, SignalEventEssence signal, boolean popupIsShown, @Nonnull DocumentParser parser) { if (checkEnterTrigger(signal) && checkCursorBetweenCurlyBraces(selectionModel)) { String text = selectionModel.getCursorPosition().getLine().getText(); int indent = StringUtils.lengthOfStartingWhitespace(text); String newLine = "\n" + StringUtils.getSpaces(indent); String emptyLine = newLine + " "; return new ExplicitAction( new DefaultAutocompleteResult(emptyLine + newLine, "", emptyLine.length())); } return super.getExplicitAction(selectionModel, signal, popupIsShown, parser); } /** * Checks trigger to be plain "Enter" key press. * * <p>"Shift-Enter" also works to avoid "sticky-shift" issue: * when someone quickly types "Shift-[" (-> "{") and then * press "Enter" while "Shift" is not depressed. */ private static boolean checkEnterTrigger(SignalEventEssence trigger) { return KeySignalType.INPUT == trigger.type && KeyCodes.KEY_ENTER == trigger.keyCode && !trigger.altKey && !trigger.ctrlKey && !trigger.metaKey; } /** * Checks that cursor is situated between curly braces. */ private static boolean checkCursorBetweenCurlyBraces(SelectionModel selectionModel) { if (!selectionModel.hasSelection()) { ReadOnlyAnchor cursor = selectionModel.getCursorAnchor(); String text = cursor.getLine().getText(); int column = cursor.getColumn(); if (column > 0 && column < text.length()) { if (text.charAt(column - 1) == '{' && text.charAt(column) == '}') { 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/code/autocomplete/codegraph/dart/DartAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/dart/DartAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.dart; import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.ExplicitAutocompleter; import com.google.collide.client.code.autocomplete.codegraph.LimitedContextFilePrefixIndex; import com.google.collide.client.codeunderstanding.CubeClient; import com.google.collide.codemirror2.SyntaxType; /** * Dart implementation for {@link CodeGraphAutocompleter} */ public class DartAutocompleter { /** * Dart Autocompleter. * * @return configured instance of Dart autocompleter */ public static CodeGraphAutocompleter create( CubeClient cubeClient, LimitedContextFilePrefixIndex contextFilePrefixIndex) { return new CodeGraphAutocompleter(SyntaxType.DART, new DartProposalBuilder(), cubeClient, contextFilePrefixIndex, new ExplicitAutocompleter()); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/dart/DartProposalBuilder.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/dart/DartProposalBuilder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.dart; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.CompletionContext; import com.google.collide.client.code.autocomplete.codegraph.ProposalBuilder; import com.google.collide.client.code.autocomplete.codegraph.TemplateProposal; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.codemirror2.DartState; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringSet; import com.google.collide.shared.util.JsonCollections; /** * Dart implementation of {@link ProposalBuilder}. */ class DartProposalBuilder extends ProposalBuilder<DartState> { DartProposalBuilder() { super(DartState.class); } @Override protected PrefixIndex<TemplateProposal> getTemplatesIndex() { return DartConstants.getInstance().getSnippetsTemplateTrie(); } @Override protected boolean checkIsThisPrefix(String prefix) { return "this.".equals(prefix); } @Override protected void addShortcutsTo(CompletionContext<DartState> context, JsonStringSet prefixes) { } @Override protected JsonArray<String> getLocalVariables(ParseResult<DartState> parseResult) { // TODO : implement. return JsonCollections.createArray(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/codegraph/dart/DartConstants.java
client/src/main/java/com/google/collide/client/code/autocomplete/codegraph/dart/DartConstants.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.codegraph.dart; import com.google.collide.client.code.autocomplete.AbstractTrie; import com.google.collide.client.code.autocomplete.PrefixIndex; import com.google.collide.client.code.autocomplete.codegraph.TemplateProposal; /** * Dart constants. */ class DartConstants { private static DartConstants instance; static DartConstants getInstance() { if (instance == null) { instance = new DartConstants(); } return instance; } private final PrefixIndex<TemplateProposal> proposalTemplateTrie; private static void addProposal(AbstractTrie<TemplateProposal> to, String name, String template) { to.put(name, new TemplateProposal(name, template)); } public PrefixIndex<TemplateProposal> getSnippetsTemplateTrie() { return proposalTemplateTrie; } private DartConstants() { AbstractTrie<TemplateProposal> temp = new AbstractTrie<TemplateProposal>(); addProposal(temp, "#source", "#source(%c);"); addProposal(temp, "#import", "#import(%c);"); addProposal(temp, "#include", "#include(%c);"); addProposal(temp, "#library", "#library(%c);"); addProposal(temp, "abstract", "abstract "); addProposal(temp, "assert", "assert(%c);"); addProposal(temp, "break", "break;"); addProposal(temp, "case", "case %c:"); addProposal(temp, "catch", "catch (%c) {%i%n}"); addProposal(temp, "class", "class %c {%i%n}"); addProposal(temp, "continue", "continue;"); addProposal(temp, "const", "const "); addProposal(temp, "default", "default:"); addProposal(temp, "do", "do {%i%c%n} while ()"); addProposal(temp, "else", "else {%n%c%n}"); addProposal(temp, "extends", "extends "); addProposal(temp, "final", "final "); addProposal(temp, "for", "for (%c;;) {%i%n}"); addProposal(temp, "for", "for (%c in %c) {%i%n}"); addProposal(temp, "function", "function %c() {%i%n}"); addProposal(temp, "get", "get %c() {%i%n}"); addProposal(temp, "if", "if (%c) {%i%n}"); addProposal(temp, "interface", "interface "); addProposal(temp, "is", "is %c"); addProposal(temp, "implements", "implements "); addProposal(temp, "native", "native "); addProposal(temp, "new", "new %c();"); addProposal(temp, "operator", "operator "); addProposal(temp, "return", "return %c;"); addProposal(temp, "set", "set %c() {%i%n}"); addProposal(temp, "static", "static "); addProposal(temp, "super", "super(%c)"); addProposal(temp, "switch", "switch (%c) {%i%n}"); addProposal(temp, "this", "this"); addProposal(temp, "throw", "throw "); addProposal(temp, "try", "try {%i%c%n}%i%ncatch() {%i%n}"); addProposal(temp, "typedef", "typedef "); addProposal(temp, "var", "var %c"); addProposal(temp, "void", "void "); addProposal(temp, "while", "while (%c) {%i%n}"); this.proposalTemplateTrie = temp; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/css/CssCompletionQuery.java
client/src/main/java/com/google/collide/client/code/autocomplete/css/CssCompletionQuery.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.css; import static com.google.collide.client.code.autocomplete.css.CompletionType.NONE; import com.google.collide.json.client.JsoArray; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.regexp.shared.SplitResult; /** * A completion query for a CSS autocompletion. Processes the relevant context * in the document. * */ public class CssCompletionQuery { private static final RegExp REGEXP_SPACES = RegExp.compile("\\s+"); private static final RegExp REGEXP_COLON = RegExp.compile(":"); private static final RegExp REGEXP_SEMICOLON = RegExp.compile(";"); /* * Depending on the query, we will either have an incomplete property or an * incomplete value. If there is an incomplete value, the property (name) is * assumed completed (or incorrect). */ private String property = ""; // Current property /* * The following two fields are used for filtering existing * properties/attributes from the list of proposals. */ private final JsoArray<String> completedProperties = JsoArray.create(); private final JsArrayString valuesAfter = JsArrayString.createArray().cast(); private final JsArrayString valuesBefore = JsArrayString.createArray().cast(); private String value = ""; private CompletionType completionType; /** * Constructs a completion query based on an incomplete string, which is * everything from the caret back to the beginning of the open CSS declaration * block. * * * @param textBefore the string to be completed */ public CssCompletionQuery(String textBefore, String textAfter) { completionType = NONE; parseContext(textBefore, textAfter); } public String getValue() { return value; } public JsArrayString getValuesAfter() { return valuesAfter; } public JsArrayString getValuesBefore() { return valuesBefore; } public JsoArray<String> getCompletedProperties() { return completedProperties; } public CompletionType getCompletionType() { return completionType; } public String getProperty() { return property; } private void parseCurrentPropertyAndValues(String incompletePropertyAndValues) { incompletePropertyAndValues = incompletePropertyAndValues.substring(incompletePropertyAndValues.indexOf('{') + 1); SplitResult subParts = REGEXP_COLON.split(incompletePropertyAndValues); // subParts must have at least one element property = subParts.get(0).trim(); if (subParts.length() > 1) { SplitResult valueParts = REGEXP_SPACES.split(subParts.get(1)); if (subParts.get(1).endsWith(" ")) { for (int i = 0; i < valueParts.length(); i++) { String trimmed = valueParts.get(i).trim(); if (!trimmed.isEmpty()) { valuesBefore.push(trimmed); } } } else { if (valueParts.length() == 1) { value = subParts.get(1).trim(); } else { value = valueParts.get(valueParts.length() - 1).trim(); for (int i = 0; i < valueParts.length() - 1; i++) { String trimmed = valueParts.get(i).trim(); if (!trimmed.isEmpty()) { valuesBefore.push(trimmed); } } } } } else if (incompletePropertyAndValues.endsWith(":")) { value = ""; } } // TODO: Do something useful with textAfter private void parseContext(String textBefore, String textAfter) { if (textBefore.isEmpty()) { completionType = CompletionType.PROPERTY; return; } else if (textBefore.endsWith("{")) { completionType = CompletionType.CLASS; return; } textBefore = textBefore.replaceAll("^\\s+", ""); // Split first on ';'. The last one is the incomplete one. SplitResult parts = REGEXP_SEMICOLON.split(textBefore); if ((textBefore.endsWith(";")) || (!parts.get(parts.length() - 1).contains(":"))) { completionType = CompletionType.PROPERTY; } else { completionType = CompletionType.VALUE; } int highestCompleteIndex = parts.length() - 2; if (textBefore.endsWith(";")) { highestCompleteIndex = parts.length() - 1; } else { parseCurrentPropertyAndValues(parts.get(parts.length() - 1)); } if (parts.length() > 1) { // Parse the completed properties, which we use for filtering. for (int i = 0; i <= highestCompleteIndex; i++) { String completePropertyAndValues = parts.get(i); SplitResult subParts = REGEXP_COLON.split(completePropertyAndValues); completedProperties.add(subParts.get(0).trim().toLowerCase()); } } // Interpret textAfter // Everything up to the first ; will be interpreted as being part of the // current property, so it'll be complete values parts = REGEXP_SEMICOLON.split(textAfter); if (parts.length() > 0) { // We assume that the property+values we are currently working on is not // completed but can be assumed to end with a newline. int newlineIndex = parts.get(0).indexOf('\n'); if (newlineIndex != -1) { String currentValues = parts.get(0).substring(0, newlineIndex); addToValuesAfter(currentValues); addToCompletedProperties(parts.get(0).substring(newlineIndex + 1)); } else { addToValuesAfter(parts.get(0)); } for (int i = 1; i < parts.length(); i++) { addToCompletedProperties(parts.get(i)); } } } private void addToCompletedProperties(String completedProps) { SplitResult completed = REGEXP_SEMICOLON.split(completedProps); for (int i = 0; i < completed.length(); i++) { int colonIndex = completed.get(i).indexOf(":"); String trimmed; if (colonIndex != -1) { trimmed = completed.get(i).substring(0, colonIndex).trim(); } else { trimmed = completed.get(i).trim(); } if (!trimmed.isEmpty()) { completedProperties.add(trimmed.toLowerCase()); } } } private void addToValuesAfter(String completedVals) { SplitResult completed = REGEXP_SPACES.split(completedVals); for (int i = 0; i < completed.length(); i++) { String trimmed = completed.get(i).trim(); if (!trimmed.isEmpty()) { valuesAfter.push(trimmed); } } } @VisibleForTesting public String getTriggeringString() { switch (completionType) { case CLASS: return ""; case PROPERTY: return getProperty(); case VALUE: return getValue(); default: return null; } } public void setCompletionType(CompletionType type) { this.completionType = 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/code/autocomplete/css/CssAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/css/CssAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.css; import static com.google.collide.client.code.autocomplete.AutocompleteResult.PopupAction.CLOSE; import static com.google.collide.client.code.autocomplete.AutocompleteResult.PopupAction.OPEN; import static com.google.collide.client.code.autocomplete.css.CompletionType.CLASS; import static com.google.collide.client.code.autocomplete.css.CompletionType.PROPERTY; import static com.google.collide.client.code.autocomplete.css.CompletionType.VALUE; import static com.google.collide.codemirror2.TokenType.NULL; import com.google.collide.client.code.autocomplete.AbstractTrie; import com.google.collide.client.code.autocomplete.AutocompleteController; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.code.autocomplete.AutocompleteResult; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.logging.Log; import com.google.collide.codemirror2.CssState; import com.google.collide.codemirror2.CssToken; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.codemirror2.Token; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.Position; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; /** * Autocompleter for CSS. Currently, this only supports CSS2. * * TODO: Support CSS3. * TODO: may be trigger on ":"? */ public class CssAutocompleter extends LanguageSpecificAutocompleter { private static final String PROPERTY_TERMINATOR = ";"; private static final String PROPERTY_SEPARATOR = ": "; private static final String CLASS_SEPARATOR = "{\n \n}"; private static final int CLASS_JUMPLENGTH = 4; private static final AbstractTrie<AutocompleteProposal> cssTrie = CssTrie.createTrie(); public static CssAutocompleter create() { return new CssAutocompleter(); } private static AutocompleteResult constructResult(String rawResult, String triggeringString) { int start = rawResult.indexOf('<'); int end = rawResult.indexOf('>'); if ((start >= 0) && (start < end)) { return new DefaultAutocompleteResult( rawResult, (end + 1), 0, (end + 1) - start, 0, CLOSE, triggeringString); } return new DefaultAutocompleteResult(rawResult, triggeringString, rawResult.length()); } private CssCompletionQuery completionQuery; private CssAutocompleter() { super(SyntaxType.CSS); } @Override public void attach( DocumentParser parser, AutocompleteController controller, PathUtil filePath) { super.attach(parser, controller, filePath); completionQuery = null; } @Override public AutocompleteResult computeAutocompletionResult(ProposalWithContext proposal) { AutocompleteProposal selectedProposal = proposal.getItem(); String triggeringString = proposal.getContext().getTriggeringString(); String name = selectedProposal.getName(); CompletionType completionType = completionQuery.getCompletionType(); if (CLASS == completionType) { // In this case implicit autocompletion workflow should trigger, // and so execution should never reach this point. Log.warn(getClass(), "Invocation of this method in not allowed for type CLASS"); return DefaultAutocompleteResult.EMPTY; } else if (PROPERTY == completionType) { String addend = name + PROPERTY_SEPARATOR + PROPERTY_TERMINATOR; int jumpLength = addend.length() - PROPERTY_TERMINATOR.length(); return new DefaultAutocompleteResult( addend, jumpLength, 0, 0, 0, OPEN, triggeringString); } else if (VALUE == completionType) { return constructResult(name, triggeringString); } Log.warn(getClass(), "Invocation of this method in not allowed for type NONE"); return DefaultAutocompleteResult.EMPTY; } /** * Creates a completion query from the position of the caret and the editor. * The completion query contains the string to complete and the type of * autocompletion. * * TODO: take care of quoted '{' and '}' */ @VisibleForTesting CssCompletionQuery updateOrCreateQuery(CssCompletionQuery completionQuery, Position cursor) { Line line = cursor.getLine(); int column = cursor.getColumn(); Line lineWithCursor = line; boolean parsingLineWithCursor = true; /* * textSoFar will contain the text of the CSS rule (only the stuff within * the curly braces). If we are not in an open rule, return false */ String textBefore = ""; while ((line != null) && (!textBefore.contains("{"))) { int lastOpen; int lastClose; String text; if (parsingLineWithCursor) { text = line.getText().substring(0, column); parsingLineWithCursor = false; } else { /* * Don't include the newline character; it is irrelevant for * autocompletion. */ text = line.getText().trim(); } textBefore = text + textBefore; lastOpen = text.lastIndexOf('{'); lastClose = text.lastIndexOf('}'); // Either we have only a } or the } appears after { if (lastOpen < lastClose) { return completionQuery; } else if ((lastOpen == -1) && (lastClose == -1)) { line = line.getPreviousLine(); } else { if (textBefore.endsWith("{")) { // opening a new css class, no text after to consider return new CssCompletionQuery(textBefore, ""); } else if (textBefore.endsWith(";") && completionQuery != null) { // we don't want to create a new query, otherwise we lose the // completed proposals completionQuery.setCompletionType(CompletionType.NONE); return completionQuery; } } } parsingLineWithCursor = true; String textAfter = ""; line = lineWithCursor; while ((line != null) && (!textAfter.contains("}"))) { int lastOpen; int lastClose; String text; if (parsingLineWithCursor) { text = line.getText().substring(column); parsingLineWithCursor = false; } else { /* * Don't include the newline character; it is irrelevant for * autocompletion. */ text = line.getText().trim(); } textAfter = textAfter + text; lastOpen = text.lastIndexOf('{'); lastClose = text.lastIndexOf('}'); // Either we have only a } or the } appears after { if (lastClose < lastOpen) { return completionQuery; } else if ((lastOpen == -1) && (lastClose == -1)) { line = line.getNextLine(); } else { if ((!textAfter.isEmpty()) && (textAfter.charAt(textAfter.length() - 1) == ';')) { return completionQuery; } } } if (textBefore.contains("{")) { textBefore = textBefore.substring(textBefore.indexOf('{') + 1); } if (textAfter.contains("}")) { textAfter = textAfter.substring(0, textAfter.indexOf('}')); } return new CssCompletionQuery(textBefore, textAfter); } /** * Finds autocompletions for a given completion query. * * @return an array of autocompletion proposals */ @Override public AutocompleteProposals findAutocompletions( SelectionModel selection, SignalEventEssence trigger) { if (selection.hasSelection()) { // Doesn't make much sense to autocomplete CSS when something is selected. return AutocompleteProposals.EMPTY; } completionQuery = updateOrCreateQuery(completionQuery, selection.getCursorPosition()); if (completionQuery == null) { return AutocompleteProposals.EMPTY; } String triggeringString = completionQuery.getTriggeringString(); if (triggeringString == null) { return AutocompleteProposals.EMPTY; } switch (completionQuery.getCompletionType()) { case PROPERTY: return new AutocompleteProposals(SyntaxType.CSS, triggeringString, CssTrie.findAndFilterAutocompletions( cssTrie, triggeringString, completionQuery.getCompletedProperties())); case VALUE: return new AutocompleteProposals(SyntaxType.CSS, triggeringString, CssPartialParser.getInstance().getAutocompletions( completionQuery.getProperty(), completionQuery.getValuesBefore(), triggeringString, completionQuery.getValuesAfter())); case CLASS: // TODO: Implement css-class autocompletions (pseudoclasses // and HTML elements). return AutocompleteProposals.EMPTY; default: return AutocompleteProposals.EMPTY; } } @Override public ExplicitAction getExplicitAction(SelectionModel selectionModel, SignalEventEssence signal, boolean popupIsShown) { if (signal.getChar() != '{') { return ExplicitAction.DEFAULT; } if (selectionModel.hasSelection()) { return ExplicitAction.DEFAULT; } DocumentParser parser = getParser(); // 1) Check we are not in block already. ParseResult<CssState> parseResult = parser.getState( CssState.class, selectionModel.getCursorPosition(), " "); if (parseResult == null) { return ExplicitAction.DEFAULT; } JsonArray<Token> tokens = parseResult.getTokens(); Preconditions.checkNotNull(tokens); Preconditions.checkState(tokens.size() > 0); CssToken lastToken = (CssToken) tokens.peek(); if ("{".equals(lastToken.getContext())) { return ExplicitAction.DEFAULT; } // 2) Check we will enter block. parseResult = parser.getState(CssState.class, selectionModel.getCursorPosition(), "{"); if (parseResult == null) { return ExplicitAction.DEFAULT; } tokens = parseResult.getTokens(); Preconditions.checkNotNull(tokens); Preconditions.checkState(tokens.size() > 0); lastToken = (CssToken) tokens.peek(); String context = lastToken.getContext(); boolean inBlock = context != null && context.endsWith("{"); if (inBlock && NULL == lastToken.getType()) { return new ExplicitAction( new DefaultAutocompleteResult(CLASS_SEPARATOR, "", CLASS_JUMPLENGTH)); } return ExplicitAction.DEFAULT; } @Override protected void pause() { super.pause(); completionQuery = null; } @Override public void cleanup() { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/autocomplete/css/CssPartialParser.java
client/src/main/java/com/google/collide/client/code/autocomplete/css/CssPartialParser.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.css; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.json.client.Jso; import com.google.collide.json.client.JsoArray; import com.google.common.annotations.VisibleForTesting; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.regexp.shared.RegExp; import elemental.js.util.JsMapFromStringToBoolean; /** * Based on the complete property list for CSS2, this partial parser parses * already existing values and proposes autocompletions for the slot where the * cursor currently is. * */ public class CssPartialParser { /** * Singleton instance. */ private static CssPartialParser instance; // TODO: What about "-.5"? private static final String NUMBER_PATTERN = "(-|\\+)?\\d+(\\.\\d+)?"; private static final String PERCENTAGE_PATTERN = "(\\d|[1-9]\\d|100)%"; private static final String BYTE_PATTERN = "(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])"; private static final String LENGTH_PATTERN = NUMBER_PATTERN + "(em|ex|in|cm|mm|pt|pc|px)"; private static final RegExp REGEXP_INTEGER = compileRegExp("(-|\\+)?\\d+"); private static final RegExp REGEXP_PERCENTAGE = compileRegExp(PERCENTAGE_PATTERN); private static final RegExp REGEXP_3_HEX = compileRegExp("#[0-9a-fA-F]{3}"); private static final RegExp REGEXP_6_HEX = compileRegExp("#[0-9a-fA-F]{6}"); private static final RegExp REGEXP_RGB_BYTES = compileRegExp( "rgb\\(" + BYTE_PATTERN + "\\,\\s*" + BYTE_PATTERN + "\\,\\s*" + BYTE_PATTERN + "\\)"); private static final RegExp REGEXP_RGB_PERCENTS = compileRegExp("rgb\\(" + PERCENTAGE_PATTERN + "\\,\\s*" + PERCENTAGE_PATTERN + "\\,\\s*" + PERCENTAGE_PATTERN + "\\)"); private static final RegExp REGEXP_ANGLE = compileRegExp(NUMBER_PATTERN + "(deg|grad|rad)"); private static final RegExp REGEXP_NUMBER = compileRegExp(NUMBER_PATTERN); private static final RegExp REGEXP_FREQUENCY = compileRegExp(NUMBER_PATTERN + "k?Hz"); private static final RegExp REGEXP_LENGTH = compileRegExp(LENGTH_PATTERN); private static final RegExp REGEXP_RECT = compileRegExp("rect\\(\\s*(" + LENGTH_PATTERN + "|auto)\\s*\\,\\s*(" + LENGTH_PATTERN + "|auto)\\s*\\,\\s*(" + LENGTH_PATTERN + "|auto)\\s*\\,\\s*(" + LENGTH_PATTERN + "|auto)\\s*\\)"); private static final String ANGLE = "<angle>"; private static final String NUMBER = "<number>"; private static final String INTEGER = "<integer>"; private static final String URI = "<uri>"; private static final String PERCENTAGE = "<percentage>"; private static final String STRING = "<string>"; private static final String COUNTER = "<counter>"; private static final String IDENTIFIER = "<identifier>"; private static final String FREQUENCY = "<frequency>"; private static final String COLOR = "<color>"; private static final String LENGTH = "<length>"; private static final String SHAPE = "<shape>"; private final JavaScriptObject allProperties; private final JavaScriptObject specialValueProposals; private final JsMapFromStringToBoolean repeatingProperties = JsMapFromStringToBoolean.create(); public static CssPartialParser getInstance() { if (instance == null) { instance = new CssPartialParser(); } return instance; } /** * Creates {@link RegExp} instance by given pattern that matches the * whole string. */ private static RegExp compileRegExp(String pattern) { return RegExp.compile("^" + pattern + "$"); } private CssPartialParser() { allProperties = setupAllProperties(); specialValueProposals = setupSpecialValueProposals(); setupRepeatingProperties(repeatingProperties); } private boolean checkIfAngle(String maybeSpecialValue) { return REGEXP_ANGLE.test(maybeSpecialValue); } private boolean checkIfNumber(String maybeSpecialValue) { return REGEXP_NUMBER.test(maybeSpecialValue); } private boolean checkIfInteger(String maybeSpecialValue) { return REGEXP_INTEGER.test(maybeSpecialValue); } private boolean checkIfUri(String maybeSpecialValue) { // TODO: This is an oversimplification. return (maybeSpecialValue.startsWith("http://") || maybeSpecialValue.startsWith("https://")); } private boolean checkIfPercentage(String maybeSpecialValue) { return REGEXP_PERCENTAGE.test(maybeSpecialValue); } private boolean checkIfString(String maybeSpecialValue) { return (((maybeSpecialValue.charAt(0) == '"') && (maybeSpecialValue.charAt(maybeSpecialValue.length() - 1) == '"')) || ((maybeSpecialValue.charAt(0) == '\'') && (maybeSpecialValue.charAt(maybeSpecialValue.length() - 1) == '\''))); } private boolean checkIfCounter(String maybeSpecialValue) { // TODO: This is a simplification. return maybeSpecialValue.startsWith("counter("); } private boolean checkIfIdentifier(String maybeSpecialValue) { // TODO: Implement this. return false; } private boolean checkIfFrequency(String maybeSpecialValue) { return REGEXP_FREQUENCY.test(maybeSpecialValue); } private boolean checkIfColor(String maybeSpecialValue) { return maybeSpecialValue.equals("aqua") || maybeSpecialValue.equals("black") || maybeSpecialValue.equals("blue") || maybeSpecialValue.equals("fuchsia") || maybeSpecialValue.equals("gray") || maybeSpecialValue.equals("green") || maybeSpecialValue.equals("lime") || maybeSpecialValue.equals("maroon") || maybeSpecialValue.equals("navy") || maybeSpecialValue.equals("olive") || maybeSpecialValue.equals("orange") || maybeSpecialValue.equals("purple") || maybeSpecialValue.equals("red") || maybeSpecialValue.equals("silver") || maybeSpecialValue.equals("teal") || maybeSpecialValue.equals("white") || maybeSpecialValue.equals("yellow") || REGEXP_3_HEX.test(maybeSpecialValue) || REGEXP_6_HEX.test(maybeSpecialValue) || REGEXP_RGB_BYTES.test(maybeSpecialValue) || REGEXP_RGB_PERCENTS.test(maybeSpecialValue); } private boolean checkIfLength(String maybeSpecialValue) { return REGEXP_LENGTH.test(maybeSpecialValue); } private boolean checkIfShape(String maybeSpecialValue) { // Note: the syntax for shape is rect(<top>, <right>, <bottom>, <left>) return REGEXP_RECT.test(maybeSpecialValue); } /** * Checks whether the passed-in string matches the format of the special value * type in question. If it does, it returns a list of proposals that should be * shown to the user for this query. * * @param maybeSpecialValue * @param specialValueType a special value type, e.g., <integer>. This method * can be called with a specialValueType value that is not one of those * special values, in which case the method returns an empty array. * @return an array of strings corresponding to the proposals that should be * shown for the special value type */ @VisibleForTesting public JsArrayString checkIfSpecialValueAndGetSpecialValueProposals( String maybeSpecialValue, String specialValueType) { JsArrayString specialValues = getSpecialValues(maybeSpecialValue); for (int i = 0; i < specialValues.length(); i++) { if (specialValues.get(i).equals(specialValueType)) { return specialValueProposals.<Jso>cast().getJsObjectField(specialValueType).cast(); } } return JavaScriptObject.createArray().cast(); } public JsoArray<AutocompleteProposal> getAutocompletions( String property, JsArrayString valuesBefore, String incomplete, JsArrayString valuesAfter) { incomplete = incomplete.toLowerCase(); boolean isRepeatingProperty = repeatingProperties.hasKey(property); JsArrayString valuesAndSpecialValuesAfter = getValuesAndSpecialValues(valuesAfter); JsArrayString valuesAndSpecialValuesBefore = getValuesAndSpecialValues(valuesBefore); JsoArray<AutocompleteProposal> proposals = JsoArray.create(); JsArray<JavaScriptObject> valuesForAllSlots = getPropertyValues(property); if (valuesForAllSlots == null) { return proposals; } int numSlots = valuesForAllSlots.length(); if (numSlots == 0) { return proposals; } int slot = valuesBefore.length(); // slots use 0-based counting if (slot >= numSlots) { // before giving up, see if the last entry is +, in which case we just // adjust the slot number JavaScriptObject lastSlotValues = valuesForAllSlots.get(numSlots - 1); JsArrayString keySet = getKeySet(lastSlotValues); if ((keySet.length() == 1) && (keySet.get(0).equals("+"))) { slot = numSlots - 1; } else { return proposals; } } JavaScriptObject valuesForSlotInQuestion = valuesForAllSlots.get(slot); JsArrayString keySet = getKeySet(valuesForSlotInQuestion); if ((keySet.length() == 1) && (keySet.get(0).equals("+"))) { valuesForSlotInQuestion = valuesForAllSlots.get(slot - 1); keySet = getKeySet(valuesForSlotInQuestion); } if (valuesForSlotInQuestion != null) { if (keySet.length() == 0) { return proposals; } for (int keyCt = 0; keyCt < keySet.length(); keyCt++) { String currentValue = keySet.get(keyCt); Boolean shouldBeIncluded = false; // TODO: Avoid using untyped native collections. JavaScriptObject triggers = valuesForSlotInQuestion.<Jso>cast().getJsObjectField(currentValue).cast(); JsArrayString keyTriggerSet = getKeySet(triggers); if (keyTriggerSet.length() == 0) { if (currentValue.charAt(0) == '<') { JsArrayString valueProposals = specialValueProposals.<Jso>cast().getJsObjectField(currentValue).cast(); if (valueProposals != null && valueProposals.length() != 0) { shouldBeIncluded = false; for (int i = 0; i < valueProposals.length(); i++) { if (valueProposals.get(i).startsWith(incomplete) && (isRepeatingProperty || !inExistingValues( currentValue, valuesAndSpecialValuesBefore, valuesAndSpecialValuesAfter))) { proposals.add(new AutocompleteProposal(valueProposals.get(i))); } } } } else { shouldBeIncluded = true; } } else { for (int keyTriggerCt = 0; keyTriggerCt < keyTriggerSet.length(); keyTriggerCt++) { String triggerValue = keyTriggerSet.get(keyTriggerCt); int triggerSlot = triggers.<Jso>cast().getIntField(triggerValue); if (triggerValue.charAt(0) == '<') { JsArrayString specialValueProposalsAfterCheck = checkIfSpecialValueAndGetSpecialValueProposals( valuesBefore.get(triggerSlot), triggerValue); if (specialValueProposalsAfterCheck.length() != 0) { shouldBeIncluded = false; for (int i = 0; i < specialValueProposalsAfterCheck.length(); i++) { if (specialValueProposalsAfterCheck.get(i).startsWith(incomplete) && (isRepeatingProperty || !inExistingValues(triggerValue, valuesAndSpecialValuesBefore, valuesAndSpecialValuesAfter))) { proposals.add(new AutocompleteProposal(specialValueProposalsAfterCheck.get(i))); } } } } else if (valuesBefore.get(triggerSlot).compareTo(triggerValue) == 0) { shouldBeIncluded = true; } } } if (shouldBeIncluded) { if (currentValue.startsWith(incomplete) && (isRepeatingProperty || !inExistingValues( currentValue, valuesAndSpecialValuesBefore, valuesAndSpecialValuesAfter))) { proposals.add(new AutocompleteProposal(currentValue)); } } } } return proposals; } private boolean inExistingValues(String currentValue, JsArrayString valuesAndSpecialValuesAfter, JsArrayString valuesAndSpecialValuesBefore) { for (int i = 0; i < valuesAndSpecialValuesAfter.length(); i++) { if (valuesAndSpecialValuesAfter.get(i).equals(currentValue)) { return true; } } for (int i = 0; i < valuesAndSpecialValuesBefore.length(); i++) { if (valuesAndSpecialValuesBefore.get(i).equals(currentValue)) { return true; } } return false; } private JsArrayString getValuesAndSpecialValues(JsArrayString existingValues) { JsArrayString valuesAndSpecialValuesAfter = JavaScriptObject.createArray().cast(); for (int i = 0; i < existingValues.length(); i++) { String value = existingValues.get(i); JsArrayString specialValues = getSpecialValues(value); if (specialValues.length() == 0) { valuesAndSpecialValuesAfter.push(value); } for (int j = 0; j < specialValues.length(); j++) { valuesAndSpecialValuesAfter.push(specialValues.get(j)); } } return valuesAndSpecialValuesAfter; } private JsArrayString getSpecialValues(String value) { JsArrayString specialValues = JavaScriptObject.createArray().cast(); if (value.isEmpty()) { return specialValues; } if (checkIfAngle(value)) { specialValues.push(ANGLE); } if (checkIfInteger(value)) { specialValues.push(INTEGER); } if (checkIfNumber(value)) { specialValues.push(NUMBER); } if (checkIfUri(value)) { specialValues.push(URI); } if (checkIfPercentage(value)) { specialValues.push(PERCENTAGE); } if (checkIfString(value)) { specialValues.push(STRING); } if (checkIfCounter(value)) { specialValues.push(COUNTER); } if (checkIfIdentifier(value)) { specialValues.push(IDENTIFIER); } if (checkIfFrequency(value)) { specialValues.push(FREQUENCY); } if (checkIfColor(value)) { specialValues.push(COLOR); } if (checkIfLength(value)) { specialValues.push(LENGTH); } if (checkIfShape(value)) { specialValues.push(SHAPE); } return specialValues; } @VisibleForTesting public JsArray<JavaScriptObject> getPropertyValues(String property) { return allProperties.<Jso>cast().getJsObjectField(property).cast(); } private native JsArrayString getKeySet(JavaScriptObject jso) /*-{ var accumulator = []; for ( var propertyName in jso) { accumulator.push(propertyName); } return accumulator; }-*/; private native JavaScriptObject setupAllProperties() /*-{ return { 'azimuth' : [ { 'left-side' : {}, 'far-left' : {}, 'center-left' : {}, 'center' : {}, 'center-right' : {}, 'right' : {}, 'far-right' : {}, 'right-side' : {}, '<angle>' : {}, 'leftwards' : {}, 'rightwards' : {}, 'inherit' : {} }, { 'behind' : { 'left-side' : 0, 'far-left' : 0, 'center-left' : 0, 'center' : 0, 'center-right' : 0, 'right' : 0, 'far-right' : 0, 'right-side' : 0, '<angle>' : 0 } } ], 'background' : [ { '<color>' : {}, 'transparent' : {}, 'inherit' : {} }, { '<uri>' : {}, 'none' : {}, 'inherit' : {} }, { 'repeat' : {}, 'repeat-x' : {}, 'repeat-y' : {}, 'no-repeat' : {}, 'inherit' : {} }, { 'scroll' : {}, 'fixed' : {}, 'inherit' : {} }, { '<percentage>' : {}, '<length>' : {}, 'left' : {}, 'center' : {}, 'right' : {}, 'inherit' : {} }, { '<percentage>' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, '<length>' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, 'top' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, 'center' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, 'bottom' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 } } ], 'background-attachment' : [ { 'scroll' : {}, 'fixed' : {}, 'inherit' : {} } ], 'background-color' : [ { '<color>' : {}, 'transparent' : {}, 'inherit' : {} } ], 'background-image' : [ { '<uri>' : {}, 'none' : {}, 'inherit' : {} } ], 'background-position' : [ { '<percentage>' : {}, '<length>' : {}, 'left' : {}, 'center' : {}, 'right' : {}, 'inherit' : {} }, { '<percentage>' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, '<length>' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, 'top' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, 'center' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 }, 'bottom' : { '<percentage>' : 0, '<length>' : 0, 'left' : 0, 'center' : 0, 'right' : 0 } } ], 'background-repeat' : [ { 'repeat' : {}, 'repeat-x' : {}, 'repeat-y' : {}, 'no-repeat' : {}, 'inherit' : {} } ], 'border-collapse' : [ { 'collapse' : {}, 'separate' : {}, 'inherit' : {} } ], 'border-color' : [ { '<color>' : {}, 'transparent' : {}, 'inherit' : {} }, { '<color>' : { '<color>' : 0, 'transparent' : 0 }, 'transparent' : { '<color>' : 0, 'transparent' : 0 } }, { '<color>' : { '<color>' : 1, 'transparent' : 1 }, 'transparent' : { '<color>' : 1, 'transparent' : 1 } }, { '<color>' : { '<color>' : 2, 'transparent' : 2 }, 'transparent' : { '<color>' : 2, 'transparent' : 2 } } ], 'border-spacing' : [ { '<length>' : {}, 'inherit' : {} }, { '<length>' : { '<length>' : 0 } } ], 'border-style' : [ { 'none' : {}, 'hidden' : {}, 'dotted' : {}, 'dashed' : {}, 'solid' : {}, 'double' : {}, 'groove' : {}, 'ridge' : {}, 'inset' : {}, 'outset' : {}, 'inherit' : {} }, { 'none' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'hidden' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'dotted' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'dashed' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'solid' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'double' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'groove' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'ridge' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'inset' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 }, 'outset' : { 'none' : 0, 'hidden' : 0, 'dotted' : 0, 'dashed' : 0, 'solid' : 0, 'double' : 0, 'groove' : 0, 'ridge' : 0, 'inset' : 0, 'outset' : 0 } }, { 'none' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'hidden' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'dotted' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'dashed' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'solid' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'double' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'groove' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'ridge' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'inset' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 }, 'outset' : { 'none' : 1, 'hidden' : 1, 'dotted' : 1, 'dashed' : 1, 'solid' : 1, 'double' : 1, 'groove' : 1, 'ridge' : 1, 'inset' : 1, 'outset' : 1 } }, { 'none' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'hidden' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'dotted' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'dashed' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'solid' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'double' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'groove' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'ridge' : { 'none' : 2, 'hidden' : 2, 'dotted' : 2, 'dashed' : 2, 'solid' : 2, 'double' : 2, 'groove' : 2, 'ridge' : 2, 'inset' : 2, 'outset' : 2 }, 'inset' : { 'none' : 2,
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/code/autocomplete/css/CompletionType.java
client/src/main/java/com/google/collide/client/code/autocomplete/css/CompletionType.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.css; /** * An enumeration of css types of autocompletions. * */ public enum CompletionType { CLASS, PROPERTY, VALUE, 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/code/autocomplete/css/CssTrie.java
client/src/main/java/com/google/collide/client/code/autocomplete/css/CssTrie.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.css; import com.google.collide.client.code.autocomplete.AbstractTrie; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.json.client.JsoArray; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; /** * Holder of all possible CSS attributes. */ public class CssTrie { private static final JsonArray<String> ELEMENTS = JsoArray.from("azimuth", "background", "background-attachment", "background-color", "background-image", "background-position", "background-repeat", "border", "border-bottom", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-collapse", "border-color", "border-left", "border-left-color", "border-left-style", "border-left-width", "border-right", "border-right-color", "border-right-style", "border-right-width", "border-spacing", "border-style", "border-top", "border-top-color", "border-top-style", "border-top-width", "border-width", "bottom", "caption-side", "clear", "clip", "color", "content", "counter-increment", "counter-reset", "cue", "cue-after", "cue-before", "cursor", "direction", "display", "elevation", "empty-cells", "float", "font", "font-family", "font-size", "font-style", "font-variant", "font-weight", "height", "left", "letter-spacing", "line-height", "list-style", "list-style-image", "list-style-position", "list-style-type", "margin", "margin-bottom", "margin-left", "margin-right", "margin-top", "max-height", "max-width", "min-height", "min-width", "orphans", "outline", "outline-color", "outline-style", "outline-width", "overflow", "padding", "padding-bottom", "padding-left", "padding-right", "padding-top", "page-break-after", "page-break-before", "page-break-inside", "pause", "pause-after", "pause-before", "pitch", "pitch-range", "play-during", "position", "quotes", "richness", "right", "speak", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "table-layout", "text-align", "text-decoration", "text-indent", "text-transform", "top", "unicode-bidi", "vertical-align", "visibility", "voice-family", "volume", "white-space", "widows", "width", "word-spacing", "z-index"); public static AbstractTrie<AutocompleteProposal> createTrie() { AbstractTrie<AutocompleteProposal> result = new AbstractTrie<AutocompleteProposal>(); for (String name : ELEMENTS.asIterable()) { result.put(name, new AutocompleteProposal(name)); } return result; } /** * Finds all autocompletions and filters them based on a) the prefix that the * user has already typed, and b) the properties that are already present. * * @param prefix the prefix of the property that the user has already typed * @param completedProperties the properties that are already in the document * for the given property * @return an array of autocompletions, or an empty array if there are no * autocompletion proposals */ public static JsonArray<AutocompleteProposal> findAndFilterAutocompletions( AbstractTrie<AutocompleteProposal> trie, String prefix, JsonArray<String> completedProperties) { prefix = prefix.toLowerCase(); JsonArray<AutocompleteProposal> allProposals = trie.search(prefix); JsonArray<AutocompleteProposal> result = JsonCollections.createArray(); for (AutocompleteProposal proposal : allProposals.asIterable()) { if (!completedProperties.contains(proposal.getName())) { result.add(proposal); } } 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/code/autocomplete/html/HtmlTagWithAttributes.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/HtmlTagWithAttributes.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; import com.google.collide.client.util.collections.SimpleStringBag; import com.google.collide.client.util.collections.StringMultiset; /** * Object that represents contents of HTML tag entity. * * <p>Actually, only tag name and attributes bag are stored. * */ public class HtmlTagWithAttributes extends DirtyStateTracker { private final String tagName; private final StringMultiset attributes = new SimpleStringBag(); public HtmlTagWithAttributes(String tagName) { this.tagName = tagName; } public String getTagName() { return tagName; } public StringMultiset getAttributes() { return attributes; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/html/XmlCodeAnalyzer.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/XmlCodeAnalyzer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; import static com.google.collide.codemirror2.TokenType.ATTRIBUTE; import static com.google.collide.codemirror2.TokenType.TAG; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.CodeAnalyzer; import com.google.collide.client.util.collections.StringMultiset; import com.google.collide.codemirror2.CodeMirror2; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.TaggableLine; import com.google.collide.shared.util.JsonCollections; /** * Analyzes token stream and builds or updates {@link HtmlTagWithAttributes}. * * <p>For each line we hold:<ol> * <li> {@link HtmlTagWithAttributes} unfinished at the beginning of line * <li> {@link HtmlTagWithAttributes} unfinished at the end of line * <li> list of attributes added to (1) in this line * </ol> * * <p>When line is reparsed:<ol> * <li> remove attributes from the list from appropriate tag and clean list * <li> set unfinished beginning tag equal to the ending tag of previous line * <li> add attributes to list until tag closes * <li> build and set unfinished tag at the end of line * </ol> * * <p> That way, during completion we have 2 cases:<ul> * <li> for tag that starts and ends in this line we need to parse it's content * <li> for tag that is unfinished (starts in previous lines or end in the * following lines) we already have parsed tag information. * </ul> * */ public class XmlCodeAnalyzer implements CodeAnalyzer { static final String TAG_START_TAG = HtmlAutocompleter.class.getName() + ".startTag"; static final String TAG_END_TAG = HtmlAutocompleter.class.getName() + ".endTag"; private static final String TAG_ATTRIBUTES = HtmlAutocompleter.class.getName() + ".attributes"; @Override public void onBeforeParse() { // Do nothing. } @Override public void onParseLine( TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens) { processLine(previousLine, line, tokens); } static void processLine( TaggableLine previousLine, TaggableLine line, @Nonnull JsonArray<Token> tokens) { // Ignore case always, as HTML == XmlCodeAnalyzer for now. final boolean ignoreCase = true; clearLine(line); HtmlTagWithAttributes tag = previousLine.getTag(TAG_END_TAG); line.putTag(TAG_START_TAG, tag); int index = 0; int size = tokens.size(); boolean inTag = false; int lastTagTokenIndex = -1; if (tag != null) { inTag = true; boolean newAttributes = false; JsonArray<String> attributes = line.getTag(TAG_ATTRIBUTES); if (attributes == null) { newAttributes = true; attributes = JsonCollections.createArray(); } StringMultiset tagAttributes = tag.getAttributes(); while (index < size) { Token token = tokens.get(index); index++; TokenType tokenType = token.getType(); if (ATTRIBUTE == tokenType) { String attribute = token.getValue(); attribute = ignoreCase ? attribute.toLowerCase() : attribute; attributes.add(attribute); tagAttributes.add(attribute); } else if (TAG == tokenType) { // Tag closing token tag.setDirty(false); inTag = false; break; } } if (newAttributes && attributes.size() != 0) { line.putTag(TAG_ATTRIBUTES, attributes); } else if (!newAttributes && attributes.size() == 0) { line.putTag(TAG_ATTRIBUTES, null); } } else { line.putTag(TAG_ATTRIBUTES, null); } while (index < size) { Token token = tokens.get(index); index++; TokenType tokenType = token.getType(); if (TAG == tokenType) { if (inTag) { if (">".equals(token.getValue()) || "/>".equals(token.getValue())) { // If type is "tag" and content is ">", this is HTML token. inTag = false; } } else { // Check that we are in html mode. if (CodeMirror2.HTML.equals(token.getMode())) { lastTagTokenIndex = index - 1; inTag = true; } } } } if (inTag) { if (lastTagTokenIndex != -1) { index = lastTagTokenIndex; Token token = tokens.get(index); index++; String tagName = token.getValue().substring(1).trim(); tag = new HtmlTagWithAttributes(tagName); StringMultiset tagAttributes = tag.getAttributes(); while (index < size) { token = tokens.get(index); index++; TokenType tokenType = token.getType(); if (ATTRIBUTE == tokenType) { String attribute = token.getValue(); tagAttributes.add(ignoreCase ? attribute.toLowerCase() : attribute); } } } // In case when document ends, but last tag is not closed we state that // tag content is "complete" - i.e. it will not be updated further. if (line.isLastLine()) { tag.setDirty(false); } line.putTag(TAG_END_TAG, tag); } else { line.putTag(TAG_END_TAG, null); } } @Override public void onAfterParse() { // Do nothing. } @Override public void onLinesDeleted(JsonArray<TaggableLine> deletedLines) { for (TaggableLine line : deletedLines.asIterable()) { clearLine(line); } } private static void clearLine(TaggableLine line) { HtmlTagWithAttributes tag = line.getTag(TAG_START_TAG); if (tag == null) { return; } tag.setDirty(true); JsonArray<String> attributes = line.getTag(TAG_ATTRIBUTES); if (attributes == null) { return; } tag.getAttributes().removeAll(attributes); attributes.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/code/autocomplete/html/HtmlAutocompleter.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/HtmlAutocompleter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; import static com.google.collide.client.code.autocomplete.html.CompletionType.ATTRIBUTE; import static com.google.collide.client.code.autocomplete.html.CompletionType.ELEMENT; import javax.annotation.Nonnull; import com.google.collide.client.code.autocomplete.AutocompleteController; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.client.code.autocomplete.AutocompleteProposals.ProposalWithContext; import com.google.collide.client.code.autocomplete.AutocompleteResult; import com.google.collide.client.code.autocomplete.DefaultAutocompleteResult; import com.google.collide.client.code.autocomplete.LanguageSpecificAutocompleter; import com.google.collide.client.code.autocomplete.SignalEventEssence; import com.google.collide.client.code.autocomplete.codegraph.CodeGraphAutocompleter; import com.google.collide.client.code.autocomplete.css.CssAutocompleter; import com.google.collide.client.code.autocomplete.html.HtmlAutocompleteProposals.HtmlProposalWithContext; import com.google.collide.client.code.autocomplete.integration.TaggableLineUtil; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.util.PathUtil; import com.google.collide.client.util.collections.StringMultiset; import com.google.collide.codemirror2.CodeMirror2; import com.google.collide.codemirror2.HtmlState; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.codemirror2.Token; import com.google.collide.codemirror2.TokenType; import com.google.collide.codemirror2.TokenUtil; import com.google.collide.codemirror2.XmlContext; import com.google.collide.codemirror2.XmlState; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.Pair; import com.google.collide.shared.TaggableLine; import com.google.collide.shared.document.Line; import com.google.collide.shared.document.Position; import com.google.collide.shared.document.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.gwt.event.dom.client.KeyCodes; /** * Autocompleter for HTML. * * */ public class HtmlAutocompleter extends LanguageSpecificAutocompleter { private static final String ELEMENT_SEPARATOR_CLOSE = ">"; private static final String ELEMENT_SELF_CLOSE = " />"; private static final String ELEMENT_SEPARATOR_OPEN_FINISHTAG = "</"; private static final String ATTRIBUTE_SEPARATOR_OPEN = "=\""; private static final String ATTRIBUTE_SEPARATOR_CLOSE = "\""; private static final HtmlTagsAndAttributes htmlAttributes = HtmlTagsAndAttributes.getInstance(); @VisibleForTesting static final AnchorType MODE_ANCHOR_TYPE = AnchorType.create(HtmlAutocompleter.class, "mode"); public static final AutocompleteResult RESULT_SLASH = new DefaultAutocompleteResult("/", "", 1); /** * Bean that holds {@link #findTag} results. */ private static class FindTagResult { /** * Index of last start-of-TAG token before cursor; -1 => not in this line. */ int startTagIndex = -1; /** * Index of last end-of-TAG token before cursor; -1 => not in this line. */ int endTagIndex = -1; /** * Token that "covers" the cursor; left token if cursor touches 2 tokens, */ Token inToken = null; /** * Number of characters between "inToken" start and the cursor position. */ int cut = 0; /** * Indicates that cursor is located inside tag. */ boolean inTag; } public static HtmlAutocompleter create(CssAutocompleter cssAutocompleter, CodeGraphAutocompleter jsAutocompleter) { return new HtmlAutocompleter(cssAutocompleter, jsAutocompleter); } /** * Finds token at cursor position and computes first and last token indexes * of surrounding tag. */ private static FindTagResult findTag(JsonArray<Token> tokens, boolean startsInTag, int column) { FindTagResult result = new FindTagResult(); result.inTag = startsInTag; // Number of tokens in line. final int size = tokens.size(); // Sum of lengths of processed tokens. int colCount = 0; // Index of next token. int index = 0; while (index < size) { Token token = tokens.get(index); colCount += token.getValue().length(); TokenType type = token.getType(); index++; if (TokenType.TAG == type) { // Toggle "inTag" flag and update tag bounds. if (result.inTag) { // Refer to XmlCodeAnalyzer parsing code notes. if (">".equals(token.getValue()) || "/>".equals(token.getValue())) { result.endTagIndex = index - 1; // Exit the loop if cursor is inside a closed tag. if (result.inToken != null) { return result; } result.inTag = false; } } else { if (CodeMirror2.HTML.equals(token.getMode())) { result.startTagIndex = index - 1; result.endTagIndex = -1; result.inTag = true; } } } // If token at cursor position is not found yet... if (result.inToken == null) { if (colCount >= column) { // We've found it at last! result.inToken = token; result.cut = colCount - column; if (!result.inTag) { // No proposals for text content. return result; } } } } return result; } /** * Builds {@link HtmlTagWithAttributes} from {@link FindTagResult} and tokens. * * <p>Scanning is similar to scanning in {@link XmlCodeAnalyzer}. */ private static HtmlTagWithAttributes buildTag( FindTagResult findTagResult, JsonArray<Token> tokens) { int index = findTagResult.startTagIndex; Token token = tokens.get(index); index++; String tagName = token.getValue().substring(1).trim(); HtmlTagWithAttributes result = new HtmlTagWithAttributes(tagName); StringMultiset tagAttributes = result.getAttributes(); while (index < findTagResult.endTagIndex) { token = tokens.get(index); index++; TokenType tokenType = token.getType(); if (TokenType.ATTRIBUTE == tokenType) { tagAttributes.add(token.getValue().toLowerCase()); } } result.setDirty(false); return result; } private CssAutocompleter cssAutocompleter; private CodeGraphAutocompleter jsAutocompleter; private DirtyStateTracker dirtyScope; private final Runnable dirtyScopeDelegate = new Runnable() { @Override public void run() { resetDirtyScope(); scheduleRequestForUpdatedProposals(); } }; private HtmlAutocompleter(CssAutocompleter cssAutocompleter, CodeGraphAutocompleter jsAutocompleter) { super(SyntaxType.HTML); this.cssAutocompleter = cssAutocompleter; this.jsAutocompleter = jsAutocompleter; } @Override protected void attach( DocumentParser parser, AutocompleteController controller, PathUtil filePath) { super.attach(parser, controller, filePath); if (cssAutocompleter != null) { cssAutocompleter.attach(parser, controller, filePath); } if (jsAutocompleter != null) { jsAutocompleter.attach(parser, controller, filePath); } } @Override public AutocompleteResult computeAutocompletionResult(ProposalWithContext proposal) { if (!(proposal instanceof HtmlProposalWithContext)) { if (proposal.getSyntaxType() == SyntaxType.JS) { return jsAutocompleter.computeAutocompletionResult(proposal); } else if (proposal.getSyntaxType() == SyntaxType.CSS) { return cssAutocompleter.computeAutocompletionResult(proposal); } else { throw new IllegalStateException( "Unexpected mode: " + proposal.getSyntaxType().getName()); } } HtmlProposalWithContext htmlProposal = (HtmlProposalWithContext) proposal; AutocompleteProposal selectedProposal = proposal.getItem(); String triggeringString = proposal.getContext().getTriggeringString(); String selectedName = selectedProposal.getName(); switch (htmlProposal.getType()) { case ELEMENT: if (htmlAttributes.isSelfClosedTag(selectedName)) { return new DefaultAutocompleteResult( selectedName + ELEMENT_SELF_CLOSE, triggeringString, selectedName.length()); } return new DefaultAutocompleteResult( selectedName + ELEMENT_SEPARATOR_CLOSE + ELEMENT_SEPARATOR_OPEN_FINISHTAG + selectedName + ELEMENT_SEPARATOR_CLOSE, triggeringString, selectedName.length() + ELEMENT_SEPARATOR_CLOSE.length()); case ATTRIBUTE: return new DefaultAutocompleteResult( selectedName + ATTRIBUTE_SEPARATOR_OPEN + ATTRIBUTE_SEPARATOR_CLOSE, triggeringString, selectedName.length() + ATTRIBUTE_SEPARATOR_OPEN.length()); default: throw new IllegalStateException( "Invocation of this method in not allowed for type " + htmlProposal.getType()); } } @Override public ExplicitAction getExplicitAction(SelectionModel selectionModel, SignalEventEssence signal, boolean popupIsShown) { Position cursor = selectionModel.getCursorPosition(); int cursorColumn = cursor.getColumn(); Line cursorLine = cursor.getLine(); String mode = getModeForColumn(cursorLine, cursorColumn); if (cssAutocompleter != null && CodeMirror2.CSS.equals(mode)) { return cssAutocompleter.getExplicitAction(selectionModel, signal, popupIsShown); } else if (jsAutocompleter != null && CodeMirror2.JAVASCRIPT.equals(mode)) { return jsAutocompleter.getExplicitAction(selectionModel, signal, popupIsShown); } else if (mode == null) { // This is possible if line is new and hasn't been processed yet. // We prefer to avoid annoying autocompletions. return ExplicitAction.DEFAULT; } char signalChar = signal.getChar(); if (signalChar == '/') { if (selectionModel.hasSelection()) { return ExplicitAction.DEFAULT; } if (cursorColumn == 0 || '<' != cursorLine.getText().charAt(cursorColumn - 1)) { return ExplicitAction.DEFAULT; } ParseResult<HtmlState> parseResult = getParser().getState(HtmlState.class, cursor, null); if (parseResult != null) { XmlState xmlState = parseResult.getState().getXmlState(); if (xmlState != null) { XmlContext xmlContext = xmlState.getContext(); if (xmlContext != null) { String tagName = xmlContext.getTagName(); if (tagName != null) { String addend = "/" + tagName + ELEMENT_SEPARATOR_CLOSE; return new ExplicitAction(new DefaultAutocompleteResult(addend, "", addend.length())); } } } } return ExplicitAction.DEFAULT; } if (!popupIsShown && (signalChar != 0) && (KeyCodes.KEY_ENTER != signalChar) && ('>' != signalChar)) { return ExplicitAction.DEFERRED_COMPLETE; } return ExplicitAction.DEFAULT; } /** * Finds autocomplete proposals based on the incomplete string. * * <p>Triggered * * <p>This method is triggered when:<ul> * <li>popup is hidden and user press ctrl-space (event consumed), * and explicit autocompletion failed * <li><b>or</b> popup is shown * </ul> */ @Override public AutocompleteProposals findAutocompletions( SelectionModel selection, SignalEventEssence trigger) { resetDirtyScope(); Position cursor = selection.getCursorPosition(); final Line line = cursor.getLine(); final int column = cursor.getColumn(); DocumentParser parser = getParser(); JsonArray<Token> tokens = parser.parseLineSync(line); if (tokens == null) { // This line has never been parsed yet. No variants. return AutocompleteProposals.EMPTY; } // We do not ruin parse results for "clean" lines. if (parser.isLineDirty(cursor.getLineNumber())) { // But "processing" of "dirty" line is harmless. XmlCodeAnalyzer.processLine(TaggableLineUtil.getPreviousLine(line), line, tokens); } String initialMode = parser.getInitialMode(line); JsonArray<Pair<Integer, String>> modes = TokenUtil.buildModes(initialMode, tokens); putModeAnchors(line, modes); String mode = TokenUtil.findModeForColumn(initialMode, modes, column); if (cssAutocompleter != null && CodeMirror2.CSS.equals(mode)) { return cssAutocompleter.findAutocompletions(selection, trigger); } else if (jsAutocompleter != null && CodeMirror2.JAVASCRIPT.equals(mode)) { return jsAutocompleter.findAutocompletions(selection, trigger); } if (selection.hasSelection()) { // Do not autocomplete in HTML when something is selected. return AutocompleteProposals.EMPTY; } HtmlTagWithAttributes tag = line.getTag(XmlCodeAnalyzer.TAG_START_TAG); boolean inTag = tag != null; if (column == 0) { // On first column we either add attribute or do nothing. if (inTag) { JsonArray<AutocompleteProposal> proposals = htmlAttributes.searchAttributes( tag.getTagName(), tag.getAttributes(), ""); return new HtmlAutocompleteProposals("", proposals, ATTRIBUTE); } return AutocompleteProposals.EMPTY; } FindTagResult findTagResult = findTag(tokens, inTag, column); if (!findTagResult.inTag || findTagResult.inToken == null) { // Ooops =( return AutocompleteProposals.EMPTY; } // If not unfinished tag at the beginning of line surrounds cursor... if (findTagResult.startTagIndex >= 0) { // Unfinished tag at he end of line may be used... if (findTagResult.endTagIndex == -1) { tag = line.getTag(XmlCodeAnalyzer.TAG_END_TAG); if (tag == null) { // Ooops =( return AutocompleteProposals.EMPTY; } } else { // Or new (temporary) object constructed. tag = buildTag(findTagResult, tokens); } } TokenType type = findTagResult.inToken.getType(); String value = findTagResult.inToken.getValue(); value = value.substring(0, value.length() - findTagResult.cut); if (TokenType.TAG == type) { value = value.substring(1).trim(); return new HtmlAutocompleteProposals( value, htmlAttributes.searchTags(value.toLowerCase()), ELEMENT); } if (TokenType.WHITESPACE == type || TokenType.ATTRIBUTE == type) { value = (TokenType.ATTRIBUTE == type) ? value : ""; JsonArray<AutocompleteProposal> proposals = htmlAttributes.searchAttributes( tag.getTagName(), tag.getAttributes(), value); dirtyScope = tag; dirtyScope.setDelegate(dirtyScopeDelegate); if (tag.isDirty()) { return AutocompleteProposals.PARSING; } return new HtmlAutocompleteProposals(value, proposals, ATTRIBUTE); } return AutocompleteProposals.EMPTY; } @Override protected void pause() { super.pause(); resetDirtyScope(); } private void resetDirtyScope() { if (dirtyScope != null) { dirtyScope.setDelegate(null); dirtyScope = null; } } @Override public void cleanup() { } /** * Updates line meta-information. * * @param line line being parsed * @param tokens tokens collected on the line */ public void updateModeAnchors(TaggableLine line, @Nonnull JsonArray<Token> tokens) { String initialMode = getParser().getInitialMode(line); JsonArray<Pair<Integer, String>> modes = TokenUtil.buildModes(initialMode, tokens); putModeAnchors(line, modes); } @VisibleForTesting String getModeForColumn(Line line, int column) { DocumentParser parser = getParser(); String mode = parser.getInitialMode(line); JsonArray<Anchor> anchors = AnchorManager.getAnchorsByTypeOrNull(line, MODE_ANCHOR_TYPE); if (anchors != null) { for (Anchor anchor : anchors.asIterable()) { if (anchor.getColumn() >= column) { // We'll use the previous mode. break; } mode = anchor.getValue(); } } return mode; } @VisibleForTesting void putModeAnchors(@Nonnull TaggableLine currentLine, @Nonnull JsonArray<Pair<Integer, String>> modes) { Preconditions.checkState(currentLine instanceof Line); // TODO: pull AnchorManager.getAnchorsByTypeOrNull to // TaggableLine interface (for decoupling). Line line = (Line) currentLine; AnchorManager anchorManager = line.getDocument().getAnchorManager(); Preconditions.checkNotNull(anchorManager); JsonArray<Anchor> oldAnchors = AnchorManager.getAnchorsByTypeOrNull(line, MODE_ANCHOR_TYPE); if (oldAnchors != null) { for (Anchor anchor : oldAnchors.asIterable()) { anchorManager.removeAnchor(anchor); } } for (Pair<Integer, String> pair : modes.asIterable()) { Anchor anchor = anchorManager.createAnchor(MODE_ANCHOR_TYPE, line, AnchorManager.IGNORE_LINE_NUMBER, pair.first); anchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); anchor.setValue(pair.second); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/html/HtmlTagsAndAttributes.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/HtmlTagsAndAttributes.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.util.collections.SkipListStringBag; import com.google.collide.client.util.collections.StringMultiset; import com.google.collide.json.client.Jso; import com.google.collide.json.client.JsoArray; 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; // TODO: Implement and use unmodifiable-sored-string-list. // TODO: Implement type-specific attributes filtering. // TODO: Implement attribute-specific autocompletion. /** * This class holds map of HTML5 tags with corresponding attributes. * */ public class HtmlTagsAndAttributes { private static HtmlTagsAndAttributes instance; private final JsonStringSet selfClosedTags; private final SkipListStringBag tags; private final JsonStringMap<SkipListStringBag> attributes = JsonCollections.createMap(); public static HtmlTagsAndAttributes getInstance() { if (instance == null) { instance = new HtmlTagsAndAttributes(); } return instance; } private HtmlTagsAndAttributes() { selfClosedTags = JsonCollections.createStringSet( makeSelfClosedTagsArray().asIterable().iterator()); tags = new SkipListStringBag(); Jso jso = makeNestedAttributesMap(); for (String tag : jso.getKeys().asIterable()) { tags.add(tag); SkipListStringBag attributesSet = new SkipListStringBag(); flattenAttributes(jso.getArrayField(tag), attributesSet); attributes.put(tag, attributesSet); } } public boolean isSelfClosedTag(String tag) { return selfClosedTags.contains(tag.toLowerCase()); } public JsonArray<AutocompleteProposal> searchTags(String prefix) { JsonArray<AutocompleteProposal> result = JsonCollections.createArray(); for (String tag : tags.search(prefix)) { if (!tag.startsWith(prefix)) { break; } // TODO: Do we need to cache that? result.add(new AutocompleteProposal(tag)); } return result; } /** * Gets autocompletions for a specific element, narrowed down by the already * present attributes and the incomplete attribute string. * * @param tag the enclosing HTML tag * @param alreadyPresentAttributes the attributes that are already present in * the editor * @param incomplete the incomplete attribute that we find autocomplete * proposals for * @return all matching autocompletion proposals */ public JsonArray<AutocompleteProposal> searchAttributes( String tag, StringMultiset alreadyPresentAttributes, String incomplete) { JsonArray<AutocompleteProposal> result = JsonCollections.createArray(); tag = tag.toLowerCase(); incomplete = incomplete.toLowerCase(); SkipListStringBag tagAttributes = attributes.get(tag); if (tagAttributes == null) { return result; } for (String attribute : tagAttributes.search(incomplete)) { if (!attribute.startsWith(incomplete)) { break; } if (alreadyPresentAttributes.contains(attribute)) { continue; } // TODO: Do we need to cache that? result.add(new AutocompleteProposal(attribute)); } return result; } private static native String devmodeWorkaround(Object f) /*-{ return f; }-*/; private void flattenAttributes(JsoArray input, SkipListStringBag output) { if (input == null) { return; } for (Object jso : input.asIterable()) { if (jso instanceof String) { output.add(devmodeWorkaround(jso)); } else { flattenAttributes((JsoArray) jso, output); } } } private static native JsoArray<String> makeSelfClosedTagsArray() /*-{ return ['area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']; }-*/; private static native Jso makeNestedAttributesMap() /*-{ var commonAttrsCore = ['accesskey', 'class', 'contenteditable', 'contextmenu', 'dir', 'draggable', 'hidden', 'id', 'lang', 'spellcheck', 'style', 'tabindex', 'title']; var commonAttrsEventHandler = ['onabort', 'onblur', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'oncontextmenu', 'ondblclick', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onformchange', 'onforminput', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onpause', 'onplay', 'onplaying', 'onprogress', 'onratechange', 'onreadystatechange', 'onscroll', 'onseeked', 'onseeking', 'onselect', 'onshow', 'onstalled', 'onsubmit', 'onsuspend', 'ontimeupdate', 'onvolumechange', 'onwaiting']; var commonAttrsXml = ['xml:lang', 'xml:space', 'xml:base']; // This is non-normative yet, but widely used by search engines already. var commonAttrsMicrodata = ['itemid', 'itemprop', 'itemref', 'itemscope', 'itemtype']; var commonAttrs = [commonAttrsCore, commonAttrsEventHandler, commonAttrsXml, commonAttrsMicrodata]; var commonAttrsAriaExpanded = ['aria-expanded']; var commonAttrsAriaActiveDescendant = ['aria-activedescendant']; var commonAttrsAriaImplicitListItem = ['aria-posinset', 'aria-setsize']; var commonAttrsAriaImplicitTh = ['aria-sort', 'aria-level', commonAttrsAriaExpanded, 'aria-readonly', 'aria-selected']; var commonAttrsAria = [commonAttrsAriaActiveDescendant, 'aria-atomic', 'aria-autocomplete', 'aria-busy', 'aria-checked', 'aria-controls', 'aria-describedby', 'aria-disabled', 'aria-dropeffect', 'aria-flowto', 'aria-grabbed', 'aria-haspopup', 'aria-hidden', 'aria-invalid', 'aria-label', 'aria-labelledby', 'aria-live', 'aria-multiline', 'aria-multiselectable', 'aria-owns', 'aria-pressed', commonAttrsAriaImplicitTh, 'aria-relevant', 'aria-required', commonAttrsAriaImplicitListItem, 'aria-valuemax', 'aria-valuemin', 'aria-valuenow', 'aria-valuetext']; var commonAttrsAriaImplicitGroup = [commonAttrsAriaExpanded, commonAttrsAriaActiveDescendant]; return { 'a' : [commonAttrs, 'name', 'href', 'target', 'rel', 'hreflang', 'media', 'type', 'ping', commonAttrsAria], 'abbr' : [commonAttrs, commonAttrsAria], 'address' : [commonAttrs, commonAttrsAriaExpanded], 'area' : [commonAttrs, 'alt','href', 'target', 'ping', 'rel', 'media', 'hreflang', 'type', 'shape', 'coords'], 'article' : [commonAttrs, 'pubdate', commonAttrsAriaExpanded], 'aside' : [commonAttrs, commonAttrsAriaExpanded], 'audio' : [commonAttrs, 'autoplay', 'autobuffer', 'controls', 'loop', 'src'], 'b' : [commonAttrs, commonAttrsAria], 'base' : [commonAttrs, 'href', 'target'], 'bdo' : [commonAttrs], 'blockquote' : [commonAttrs, commonAttrsAria, 'cite'], 'body' : [commonAttrs, commonAttrsAriaExpanded, 'onafterprint', 'onbeforeprint', 'onbeforeunload', 'onhashchange', 'onmessage', 'onoffline', 'ononline', 'onpopstate', 'onredo', 'onresize', 'onstorage', 'onundo', 'onunload'], 'br' : [commonAttrs], 'button' : [commonAttrs, commonAttrsAria, 'name', 'disabled', 'form', 'type', 'value', 'formaction', 'autofocus', 'formenctype', 'formmethod', 'formtarget', 'formnovalidate'], 'canvas' : [commonAttrs, commonAttrsAria, 'height', 'width'], 'caption' : [commonAttrs, commonAttrsAriaExpanded], 'cite' : [commonAttrs, commonAttrsAria], 'code' : [commonAttrs, commonAttrsAria], 'col' : [commonAttrs, 'span'], 'colgroup' : [commonAttrs, 'span'], 'command' : [commonAttrs, 'type', 'label', 'icon', 'disabled', 'radiogroup', 'checked'], 'datalist' : [commonAttrs], 'dd' : [commonAttrs, commonAttrsAria], 'del' : [commonAttrs, 'cite', 'datetime'], 'details' : [commonAttrs, commonAttrsAriaExpanded, 'open'], 'dfn' : [commonAttrs, commonAttrsAria], 'dialog' : [commonAttrs, commonAttrsAriaExpanded], 'div' : [commonAttrs, commonAttrsAria], 'dl' : [commonAttrs, commonAttrsAria], 'dt' : [commonAttrs, commonAttrsAria], 'em' : [commonAttrs, commonAttrsAria], 'embed' : [commonAttrs, 'src', 'type', 'height', 'width'], 'fieldset' : [commonAttrs, commonAttrsAriaImplicitGroup, 'name', 'disabled', 'form'], 'figure' : [commonAttrs], 'footer' : [commonAttrs, commonAttrsAriaExpanded], 'form' : [commonAttrs, commonAttrsAriaExpanded, 'action', 'method', 'enctype', 'name', 'accept-charset', 'novalidate', 'target', 'autocomplete'], 'h1' : [commonAttrs], 'h2' : [commonAttrs], 'h3' : [commonAttrs], 'h4' : [commonAttrs], 'h5' : [commonAttrs], 'h6' : [commonAttrs], 'head' : [commonAttrs], 'header' : [commonAttrs, commonAttrsAriaExpanded], 'hgroup' : [commonAttrs], 'hr' : [commonAttrs], 'html' : [commonAttrs, 'manifest'], 'i' : [commonAttrs, commonAttrsAria], 'iframe' : [commonAttrs, commonAttrsAria, 'src', 'name', 'width', 'height', 'sandbox', 'seamless'], 'img' : [commonAttrs, commonAttrsAria, 'src', 'alt', 'height', 'width', 'usemap', 'ismap', 'border'], 'input' : [commonAttrs, commonAttrsAria, 'disabled', 'form', 'type', 'maxlength', 'readonly', 'size', 'value', 'autocomplete', 'autofocus', 'list', 'pattern', 'required', 'placeholder', 'checked', 'formaction', 'autofocus', 'formenctype', 'formmethod', 'formtarget', 'formnovalidate', 'multiple', 'accept', 'alt', 'src', 'height', 'width', 'list', 'min', 'max', 'step', 'readonly'], 'ins' : [commonAttrs, 'cite', 'datetime'], 'kbd' : [commonAttrs, commonAttrsAria], 'keygen' : [commonAttrs, 'challenge', 'keytype', 'autofocus', 'name', 'disabled', 'form'], 'label' : [commonAttrs, commonAttrsAriaExpanded, 'for', 'form'], 'legend' : [commonAttrs, commonAttrsAriaExpanded], 'li' : [commonAttrs, commonAttrsAria, 'value'], 'link' : [commonAttrs, 'href', 'rel', 'hreflang', 'media', 'type', 'sizes'], 'map' : [commonAttrs, 'name'], 'mark' : [commonAttrs], 'menu' : [commonAttrs, 'type', 'label'], 'meta' : [commonAttrs, 'name', 'content', 'http-equiv', 'content', 'charset'], 'meter' : [commonAttrs, 'value', 'min', 'low', 'high', 'max', 'optimum'], 'nav' : [commonAttrs, commonAttrsAriaExpanded], 'noscript' : [commonAttrs], 'object' : [commonAttrs, commonAttrsAria, 'data', 'type', 'height', 'width', 'usemap', 'name', 'form'], 'ol' : [commonAttrs, commonAttrsAria, 'start', 'reversed'], 'optgroup' : [commonAttrs, 'label', 'disabled'], 'option' : [commonAttrs, 'disabled', 'selected', 'label', 'value'], 'output' : [commonAttrs, commonAttrsAriaExpanded, 'name', 'form', 'for'], 'p' : [commonAttrs, commonAttrsAria], 'param' : [commonAttrs, 'name', 'value'], 'pre' : [commonAttrs, commonAttrsAria], 'progress' : [commonAttrs, 'value', 'max'], 'q' : [commonAttrs, commonAttrsAria, 'cite'], 'rp' : [commonAttrs, commonAttrsAria], 'rt' : [commonAttrs, commonAttrsAria], 'ruby' : [commonAttrs, commonAttrsAria], 'samp' : [commonAttrs, commonAttrsAria], 'script' : [commonAttrs, 'src', 'defer', 'async', 'type', 'charset', 'language'], 'section' : [commonAttrs, commonAttrsAriaExpanded], 'select' : [commonAttrs, 'name', 'disabled', 'form', 'size', 'multiple'], 'small' : [commonAttrs, commonAttrsAria], 'source' : [commonAttrs, 'src', 'type', 'media'], 'span' : [commonAttrs, commonAttrsAria], 'strong' : [commonAttrs, commonAttrsAria], 'style' : [commonAttrs, 'type', 'media', 'scoped'], 'sub' : [commonAttrs], 'sup' : [commonAttrs], 'table' : [commonAttrs, commonAttrsAria, 'summary'], 'tbody' : [commonAttrs], 'td' : [commonAttrs, commonAttrsAria, 'colspan', 'rowspan', 'headers'], 'textarea' : [commonAttrs, ' name', 'disabled', 'form', 'readonly', 'maxlength', 'autofocus', 'required', 'placeholder', 'rows', 'wrap', 'cols'], 'tfoot' : [commonAttrs], 'th' : [commonAttrs, commonAttrsAriaImplicitTh, 'scope', 'colspan', 'rowspan', 'headers'], 'thead' : [commonAttrs], 'time' : [commonAttrs, 'datetime'], 'title' : [commonAttrs], 'tr' : [commonAttrs, commonAttrsAria], 'track' : [commonAttrs, 'default', 'kind', 'label', 'src', 'srclang'], 'ul' : [commonAttrs, commonAttrsAria], 'var' : [commonAttrs, commonAttrsAria], 'video' : [commonAttrs, 'autoplay', 'autobuffer', 'controls', 'loop', 'poster', 'height', 'width', 'src'], 'wbr' : [commonAttrs] }; }-*/; }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/autocomplete/html/CompletionType.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/CompletionType.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; /** * An enumeration of html types of autocompletions. * */ public enum CompletionType { ELEMENT, ATTRIBUTE, 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/code/autocomplete/html/HtmlAutocompleteProposals.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/HtmlAutocompleteProposals.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; import com.google.collide.client.code.autocomplete.AutocompleteProposal; import com.google.collide.client.code.autocomplete.AutocompleteProposals; import com.google.collide.codemirror2.SyntaxType; import com.google.collide.json.shared.JsonArray; import com.google.common.base.Preconditions; /** * Html-specific implementation. */ public class HtmlAutocompleteProposals extends AutocompleteProposals { static class HtmlProposalWithContext extends ProposalWithContext { private final CompletionType type; public HtmlProposalWithContext( AutocompleteProposal proposal, Context context, CompletionType type) { super(SyntaxType.HTML, proposal, context); this.type = type; } public CompletionType getType() { return type; } } private final CompletionType type; public HtmlAutocompleteProposals( String context, JsonArray<AutocompleteProposal> items, CompletionType type) { super(SyntaxType.HTML, context, items); this.type = type; } @Override public ProposalWithContext select(AutocompleteProposal proposal) { Preconditions.checkState(items.contains(proposal)); return new HtmlProposalWithContext(proposal, context, 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/code/autocomplete/html/DirtyStateTracker.java
client/src/main/java/com/google/collide/client/code/autocomplete/html/DirtyStateTracker.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.autocomplete.html; import javax.annotation.Nullable; /** * Class that tracks "dirty" state and sends notifications to delegate. */ public class DirtyStateTracker { /** * Flag that indicates that parsing of this tag is not finished yet. */ private boolean dirty; /** * Delegate to be notified when object becomes "clean". */ private Runnable delegate; public DirtyStateTracker() { setDirty(true); } public boolean isDirty() { return dirty; } protected void setDirty(boolean dirty) { this.dirty = dirty; if (!dirty && delegate != null) { delegate.run(); } } public void setDelegate(@Nullable Runnable delegate) { this.delegate = delegate; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/parenmatch/ParenMatchHighlighter.java
client/src/main/java/com/google/collide/client/code/parenmatch/ParenMatchHighlighter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.parenmatch; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.ViewportModel; import com.google.collide.client.editor.renderer.LineRenderer; import com.google.collide.client.editor.renderer.Renderer; import com.google.collide.client.editor.renderer.SingleChunkLineRenderer; import com.google.collide.client.editor.search.SearchTask; import com.google.collide.client.editor.search.SearchTask.SearchDirection; import com.google.collide.client.editor.selection.SelectionModel; import com.google.collide.client.editor.selection.SelectionModel.CursorListener; import com.google.collide.client.util.BasicIncrementalScheduler; import com.google.collide.client.util.IncrementalScheduler; 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.AnchorManager; import com.google.collide.shared.document.anchor.AnchorType; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar; import com.google.collide.shared.util.RegExpUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; 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.user.client.Timer; /* * TODO : Make this language specific and utilize code * understanding. */ /** * Highlights matching character for (), {}, [], and <> when the cursor is next * to one of them. */ public class ParenMatchHighlighter { /** Opening paren characters. */ public static final String OPEN_PARENS = "(<[{"; /** * Closing paren characters. {@link #CLOSE_PARENS}[i] must be the closing * match for {@link #OPEN_PARENS}[i]. */ public static final String CLOSE_PARENS = ")>]}"; static final AnchorType MATCH_ANCHOR_TYPE = AnchorType.create(ParenMatchHighlighter.class, "matchAnchor"); /** * Paren match highlighting CSS. */ public interface Css extends Editor.EditorSharedCss { String match(); } /** * Paren match highlighting resources. */ public interface Resources extends ClientBundle { @Source({"ParenMatchHighlighter.css", "collide/client/common/constants.css"}) Css parenMatchHighlighterCss(); } /** * Handler for processing each line during the search. */ private class SearchTaskHandler implements SearchTask.SearchTaskExecutor { private Line startLine; private int cursorColumn; private SearchDirection direction; private char searchChar; private char cancelChar; private int matchCount; private RegExp regExp; /** * Initialize the search parameters. * * @param startLine the line the search will start at. * @param cursorColumn the column where the paren character was found. * @param direction the direction to search, depending on whether we're * looking for the closing or opening paren. * @param searchChar the char we are looking for that opens or closes the * found paren * @param cancelChar the char we found. If found again, we must find it's * match before we find the original paren's match. */ public void initialize(Line startLine, int cursorColumn, SearchDirection direction, char searchChar, char cancelChar) { this.startLine = startLine; this.cursorColumn = cursorColumn; this.direction = direction; this.searchChar = searchChar; this.cancelChar = cancelChar; if (searchChar == '[' || searchChar == ']') { this.regExp = RegExp.compile("\\[|\\]", "g"); } else { // searching ( or ) -> [(]|[)] this.regExp = RegExp.compile("[" + this.searchChar + "]|[" + this.cancelChar + "]", "g"); } // we start at 1 and try to get down to 0 by finding the actual match. this.matchCount = 1; } @Override public boolean onSearchLine(Line line, int number, boolean shouldRenderLine) { String lineText= line.getText(); /* * Set match to -1 since we call getNextMatch with match + 1 to exclude a * found match from the next round. */ int match = -1; if (direction == SearchDirection.DOWN) { if (line == startLine) { // the - 1 is to make sure we include the character at the cursor. match = cursorColumn - 1; } MatchResult result; while ((result = RegExpUtils.findMatchAfterIndex(regExp, lineText, match)) != null) { match = result.getIndex(); if (checkForMatch(line, number, match, shouldRenderLine)) { return false; } } } else { int endColumn = line.length() - 1; if (line == startLine) { endColumn = cursorColumn - 2; } // first get all matches JsonArray<Integer> matches = JsonCollections.createArray(); MatchResult result; while ((result = RegExpUtils.findMatchAfterIndex(regExp, lineText, match)) != null) { match = result.getIndex(); if (match <= endColumn) { matches.add(match); } else { break; } } // then iterate backwards through them /** * TODO : look for a faster way to do this such that we * don't have to iterate back through them */ for (int i = matches.size() - 1; i >= 0; i--) { if (checkForMatch(line, number, matches.get(i), shouldRenderLine)) { return false; } } } return true; } /** * Check if this character is the match we are looking for. */ private boolean checkForMatch(Line line, int number, int column, boolean shouldRenderLine) { char nextChar = line.getText().charAt(column); if (nextChar == searchChar) { matchCount--; } else if (nextChar == cancelChar) { matchCount++; } if (matchCount == 0) { matchAnchor = anchorManager.createAnchor(MATCH_ANCHOR_TYPE, line, number, column); // when testing, css is null matchRenderer = SingleChunkLineRenderer.create(matchAnchor, matchAnchor, css.match()); renderer.addLineRenderer(matchRenderer); if (shouldRenderLine) { renderer.requestRenderLine(line); } return true; } return false; } } /** * A helper class to handle client events and listeners. This allows all client and GWT * functionality to be mocked out in the tests by hiding the implementation details of the * {@link Timer}. */ static class ParenMatchHelper implements ListenerRegistrar<CursorListener> { CursorListener cursorListener; Remover remover; final SelectionModel selectionModel; final Timer timer = new Timer() { @Override public void run() { if (cursorListener == null) { return; } LineInfo cursorLine = new LineInfo(selectionModel.getCursorLine(), selectionModel.getCursorLineNumber()); int cursorColumn = selectionModel.getCursorColumn(); cursorListener.onCursorChange(cursorLine, cursorColumn, true); } }; public ParenMatchHelper(SelectionModel model) { this.selectionModel = model; } void register() { remover = selectionModel.getCursorListenerRegistrar().add(new CursorListener() { @Override public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) { timer.schedule(50); } }); } void cancelTimer() { timer.cancel(); } @Override public ListenerRegistrar.Remover add(CursorListener listener) { Preconditions.checkArgument(this.cursorListener == null, "Can't register two listeners"); this.cursorListener = listener; register(); return new Remover() { @Override public void remove() { remover.remove(); cursorListener = null; } }; } @Override public void remove(CursorListener listener) { throw new UnsupportedOperationException("The remover must be used to remove the listener"); } } public static ParenMatchHighlighter create( Document document, ViewportModel viewportModel, AnchorManager anchorManager, Resources res, Renderer renderer, final SelectionModel selection) { final IncrementalScheduler scheduler = new BasicIncrementalScheduler(100, 5000); ParenMatchHelper helper = new ParenMatchHelper(selection); return new ParenMatchHighlighter( document, viewportModel, anchorManager, res, renderer, scheduler, helper); } private final AnchorManager anchorManager; private final Renderer renderer; private final IncrementalScheduler scheduler; private final SearchTask searchTask; private final SearchTaskHandler searchTaskHandler; private final Css css; private final ListenerRegistrar<CursorListener> listenerRegistrar; private final CursorListener cursorListener; private ListenerRegistrar.Remover cursorListenerRemover; private Anchor matchAnchor; private LineRenderer matchRenderer; @VisibleForTesting ParenMatchHighlighter(Document document, ViewportModel viewportModel, AnchorManager anchorManager, Resources res, Renderer renderer, IncrementalScheduler scheduler, ListenerRegistrar<CursorListener> listenerRegistrar) { this.anchorManager = anchorManager; this.renderer = renderer; this.scheduler = scheduler; this.listenerRegistrar = listenerRegistrar; searchTask = new SearchTask(document, viewportModel, scheduler); searchTaskHandler = new SearchTaskHandler(); css = res.parenMatchHighlighterCss(); cursorListener = new CursorListener() { @Override public void onCursorChange(LineInfo lineInfo, int column, boolean isExplicitChange) { cancel(); maybeSearch(lineInfo, column); } }; cursorListenerRemover = this.listenerRegistrar.add(cursorListener); } /** * Enable or disable the match highlighter. By default it's enabled. */ public void setEnabled(boolean enabled) { Preconditions.checkNotNull( cursorListenerRemover, "can't enable when cursorListenerRemover is null"); if (enabled) { cursorListenerRemover = listenerRegistrar.add(cursorListener); } else { cancel(); cursorListenerRemover.remove(); } } /** * Cancel the current matching - both the search and any displayed matches. */ public void cancel() { scheduler.cancel(); searchTask.cancelTask(); if (matchRenderer != null) { renderer.removeLineRenderer(matchRenderer); renderer.requestRenderLine(matchAnchor.getLine()); anchorManager.removeAnchor(matchAnchor); matchRenderer = null; } } public void teardown() { cancel(); cursorListenerRemover.remove(); } /** * Checks if there is a paren to match at the cursor and starts a search if * so. * * @param cursorLine * @param cursorColumn */ private void maybeSearch(LineInfo cursorLine, int cursorColumn) { if (cursorColumn > 0) { char cancelChar = cursorLine.line().getText().charAt(cursorColumn - 1); int openIndex = OPEN_PARENS.indexOf(cancelChar); if (openIndex >= 0) { search(SearchDirection.DOWN, CLOSE_PARENS.charAt(openIndex), cancelChar, cursorLine, cursorColumn); return; } int closeIndex = CLOSE_PARENS.indexOf(cancelChar); if (closeIndex >= 0) { search(SearchDirection.UP, OPEN_PARENS.charAt(closeIndex), cancelChar, cursorLine, cursorColumn); return; } } } /** * Starts the search for the matching paren. * * @param direction the direction to search in * @param searchChar the character we want to match * @param cancelChar the character we found, which if we find again we need to * find its match first. * @param cursorLine the line where the to-be-matched character was found * @param column the column to the right of the to-be-matched character */ @VisibleForTesting protected void search(final SearchDirection direction, final char searchChar, final char cancelChar, final LineInfo cursorLine, final int column) { searchTaskHandler.initialize(cursorLine.line(), column, direction, searchChar, cancelChar); searchTask.searchDocumentStartingAtLine(searchTaskHandler, null, direction, cursorLine); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/popup/EditorPopupController.java
client/src/main/java/com/google/collide/client/code/popup/EditorPopupController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.popup; import javax.annotation.Nullable; 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.renderer.SingleChunkLineRenderer; import com.google.collide.client.ui.menu.AutoHideComponent; import com.google.collide.client.ui.menu.PositionController.HorizontalAlign; import com.google.collide.client.ui.menu.PositionController.Position; import com.google.collide.client.ui.menu.PositionController.PositionerBuilder; import com.google.collide.client.ui.menu.PositionController.VerticalAlign; import com.google.collide.client.ui.popup.Popup; 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.anchor.Anchor; import com.google.collide.shared.document.anchor.AnchorType; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.util.Timer; /** * Controller for the editor-wide popup. */ public class EditorPopupController { private static final AnchorType START_ANCHOR_TYPE = AnchorType.create( EditorPopupController.class, "startAnchor"); private static final AnchorType END_ANCHOR_TYPE = AnchorType.create( EditorPopupController.class, "endAnchor"); /** * Interface for specifying an arbitrary renderer for the popup. */ public interface PopupRenderer { /** * @return rendered content of the popup */ Element renderDom(); } /** * Interface for controlling the popup after it has been shown * or scheduled to be shown. */ public interface Remover { /** * @return true if this popup is currently visible or timer is running * to make it visible */ public boolean isVisibleOrPending(); /** * Hides this popup, if it is currently shown or cancels pending show. */ public void remove(); } public static EditorPopupController create(Popup.Resources resources, Editor editor) { return new EditorPopupController(Popup.create(resources), editor); } private final Editor editor; private final Popup popup; /** Used to change the position of the popup each time it is shown */ private final PositionerBuilder positionerBuilder; private Remover currentPopupRemover; /** * A DIV that floats on top of the editor area. We attach the popup to this * element. */ private final Element popupDummyElement; /** * The {@link #popupDummyElement} is anchored between {@code #startAnchor} and * {@link #endAnchor} in the {@link #document} document. These variables are * tracked to properly detach the anchors from the original document. */ private Anchor startAnchor; private Anchor endAnchor; private Document document; private final Anchor.ShiftListener anchorShiftListener = new Anchor.ShiftListener() { @Override public void onAnchorShifted(Anchor anchor) { updatePopupDummyElementWidth(); } }; private final Buffer.ScrollListener scrollListener = new Buffer.ScrollListener() { @Override public void onScroll(Buffer buffer, int scrollTop) { hide(); } }; private EditorPopupController(Popup popup, Editor editor) { this.popup = popup; this.editor = editor; this.popupDummyElement = createPopupDummyElement(editor.getBuffer().getEditorLineHeight()); this.positionerBuilder = new PositionerBuilder().setPosition(Position.NO_OVERLAP) .setHorizontalAlign(HorizontalAlign.MIDDLE); popup.setAutoHideHandler(new AutoHideComponent.AutoHideHandler() { @Override public void onHide() { hide(); } public void onShow() { // do nothing } }); } public void cleanup() { hide(); } private static Element createPopupDummyElement(int lineHeight) { Element element = Elements.createDivElement(); CSSStyleDeclaration style = element.getStyle(); style.setDisplay(CSSStyleDeclaration.Display.INLINE_BLOCK); style.setPosition(CSSStyleDeclaration.Position.ABSOLUTE); style.setWidth(0, CSSStyleDeclaration.Unit.PX); style.setHeight(lineHeight, CSSStyleDeclaration.Unit.PX); style.setZIndex(1); // We do this so that custom CSS class (provided by textCssClassName in the #showPopup) // with cursor:pointer should work correctly. style.setProperty("pointer-events", "none"); return element; } private void attachPopupDummyElement(LineInfo lineInfo, int startColumn, int endColumn) { // Detach from the old document first, just in case. detachPopupDummyElement(); document = editor.getDocument(); startAnchor = document.getAnchorManager().createAnchor(START_ANCHOR_TYPE, lineInfo.line(), lineInfo.number(), startColumn); startAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); startAnchor.getShiftListenerRegistrar().add(anchorShiftListener); endAnchor = document.getAnchorManager().createAnchor(END_ANCHOR_TYPE, lineInfo.line(), lineInfo.number(), endColumn); endAnchor.setRemovalStrategy(Anchor.RemovalStrategy.SHIFT); endAnchor.getShiftListenerRegistrar().add(anchorShiftListener); editor.getBuffer().addAnchoredElement(startAnchor, popupDummyElement); updatePopupDummyElementWidth(); } private void updatePopupDummyElementWidth() { if (startAnchor != null && endAnchor != null) { Buffer buffer = editor.getBuffer(); int left = buffer.calculateColumnLeft(startAnchor.getLine(), startAnchor.getColumn()); popupDummyElement.getStyle().setWidth( buffer.calculateColumnLeft(endAnchor.getLine(), endAnchor.getColumn() + 1) - left, CSSStyleDeclaration.Unit.PX); } } private void detachPopupDummyElement() { if (startAnchor != null) { startAnchor.getShiftListenerRegistrar().remove(anchorShiftListener); editor.getBuffer().removeAnchoredElement(startAnchor, popupDummyElement); document.getAnchorManager().removeAnchor(startAnchor); startAnchor = null; } if (endAnchor != null) { endAnchor.getShiftListenerRegistrar().remove(anchorShiftListener); document.getAnchorManager().removeAnchor(endAnchor); endAnchor = null; } document = null; } /** * Shows the popup anchored to a given position in the line. * * @param lineInfo the line to anchor the popup to * @param startColumn start column in the line, inclusive * @param endColumn end column in the line, inclusive * @param textCssClassName class name to highlight the anchor, or {@code null} * if this is not needed * @param renderer the popup renderer * @param popupPartnerElements array of partner element of the popup * (i.e. those DOM elements where mouse hover will not trigger closing * the popup), or {@code null} if no additional partners should be * considered. Also see {@link AutoHideComponent#addPartner} * @param verticalAlign vertical align of the popup related to the line * @param shouldCaptureOutsideClickOnClose whether the popup should capture * and prevent clicks outside of it when it closes itself * @return an instance of {@link Remover} to control the popup */ public Remover showPopup(LineInfo lineInfo, int startColumn, int endColumn, @Nullable String textCssClassName, PopupRenderer renderer, final @Nullable JsonArray<Element> popupPartnerElements, final VerticalAlign verticalAlign, boolean shouldCaptureOutsideClickOnClose, int delayMs) { hide(); attachPopupDummyElement(lineInfo, startColumn, endColumn); final SingleChunkLineRenderer lineRenderer = textCssClassName == null ? null : SingleChunkLineRenderer.create(startAnchor, endAnchor, textCssClassName); popup.setContentElement(renderer.renderDom()); popup.setCaptureOutsideClickOnClose(shouldCaptureOutsideClickOnClose); setPopupPartnersEnabled(popupPartnerElements, true); final Timer showTimer = new Timer() { @Override public void run() { positionerBuilder.setVerticalAlign(verticalAlign); popup.show(positionerBuilder.buildAnchorPositioner(popupDummyElement)); if (lineRenderer != null) { editor.addLineRenderer(lineRenderer); requestRenderLines(lineRenderer); } } }; if (delayMs <= 0) { showTimer.run(); } else { showTimer.schedule(delayMs); } final com.google.collide.shared.util.ListenerRegistrar.Remover scrollListenerRemover = editor.getBuffer().getScrollListenerRegistrar().add(scrollListener); return (currentPopupRemover = new Remover() { @Override public boolean isVisibleOrPending() { return this == currentPopupRemover; } @Override public void remove() { showTimer.cancel(); if (isVisibleOrPending()) { currentPopupRemover = null; detachPopupDummyElement(); setPopupPartnersEnabled(popupPartnerElements, false); popup.destroy(); if (lineRenderer != null) { editor.removeLineRenderer(lineRenderer); requestRenderLines(lineRenderer); } scrollListenerRemover.remove(); } } }); } public void cancelPendingHide() { popup.cancelPendingHide(); } private void requestRenderLines(SingleChunkLineRenderer lineRenderer) { for (int i = lineRenderer.startLine(); i <= lineRenderer.endLine(); ++i) { editor.getRenderer().requestRenderLine( editor.getDocument().getLineFinder().findLine(i).line()); } } private void setPopupPartnersEnabled(@Nullable JsonArray<Element> partnerElements, boolean enable) { if (partnerElements != null) { for (int i = 0, n = partnerElements.size(); i < n; ++i) { Element element = partnerElements.get(i); if (enable) { popup.addPartner(element); popup.addPartnerClickTargets(element); } else { popup.removePartner(element); popup.removePartnerClickTargets(element); } } } } /** * Hides the popup if visible. */ public void hide() { if (currentPopupRemover != null) { currentPopupRemover.remove(); currentPopupRemover = 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/NoDebuggerApi.java
client/src/main/java/com/google/collide/client/code/debugging/NoDebuggerApi.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.PauseOnExceptionsState; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObjectId; /** * Implements {@link DebuggerApi} when no API is available in the browser. * */ public class NoDebuggerApi implements DebuggerApi { @Override public boolean isDebuggerAvailable() { return false; } @Override public String getDebuggingExtensionUrl() { return null; } @Override public void runDebugger(String sessionId, String url) { } @Override public void shutdownDebugger(String sessionId) { } @Override public void setBreakpointByUrl(String sessionId, BreakpointInfo breakpointInfo) { } @Override public void removeBreakpoint(String sessionId, String breakpointId) { } @Override public void setBreakpointsActive(String sessionId, boolean active) { } @Override public void setPauseOnExceptions(String sessionId, PauseOnExceptionsState state) { } @Override public void pause(String sessionId) { } @Override public void resume(String sessionId) { } @Override public void stepInto(String sessionId) { } @Override public void stepOut(String sessionId) { } @Override public void stepOver(String sessionId) { } @Override public void requestRemoteObjectProperties(String sessionId, RemoteObjectId remoteObjectId) { } @Override public void setRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { } @Override public void setRemoteObjectPropertyEvaluatedOnCallFrame(String sessionId, CallFrame callFrame, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression) { } @Override public void removeRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName) { } @Override public void renameRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String oldName, String newName) { } @Override public void evaluateExpression(String sessionId, String expression) { } @Override public void evaluateExpressionOnCallFrame(String sessionId, CallFrame callFrame, String expression) { } @Override public void requestAllCssStyleSheets(String sessionId) { } @Override public void setStyleSheetText(String sessionId, String styleSheetId, String text) { } @Override public void sendCustomMessage(String sessionId, String message) { } @Override public void addDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener) { } @Override public void removeDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener) { } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggingSidebarControlsPane.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarControlsPane.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.menu.PositionController; 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 com.google.gwt.resources.client.ImageResource; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * Debugging sidebar controls pane. * * TODO: i18n for the UI strings? * */ public class DebuggingSidebarControlsPane extends UiComponent<DebuggingSidebarControlsPane.View> { public interface Css extends CssResource { String root(); String buttonEnabled(); String pauseButton(); String resumeButton(); String stepOverButton(); String stepIntoButton(); String stepOutButton(); } interface Resources extends ClientBundle, Tooltip.Resources { @Source("DebuggingSidebarControlsPane.css") Css workspaceEditorDebuggingSidebarControlsPaneCss(); @Source("pauseButton.png") ImageResource pauseButton(); @Source("resumeButton.png") ImageResource resumeButton(); @Source("stepOverButton.png") ImageResource stepOverButton(); @Source("stepIntoButton.png") ImageResource stepIntoButton(); @Source("stepOutButton.png") ImageResource stepOutButton(); } enum DebuggerCommand { PAUSE, RESUME, STEP_OVER, STEP_INTO, STEP_OUT } /** * Listener of this pane's events. */ interface Listener { void onDebuggerCommand(DebuggerCommand command); } /** * The view for the sidebar controls pane. */ static class View extends CompositeView<ViewEvents> { private final Resources resources; private final Css css; private final Element pauseButton; private final Element resumeButton; private final Element stepOverButton; private final Element stepIntoButton; private final Element stepOutButton; private class ButtonClickListener implements EventListener { private final DebuggerCommand command; private ButtonClickListener(DebuggerCommand command) { this.command = command; } @Override public void handleEvent(Event evt) { Element target = (Element) evt.getTarget(); if (target.hasClassName(css.buttonEnabled())) { getDelegate().onDebuggerCommand(command); } } } View(Resources resources) { this.resources = resources; css = resources.workspaceEditorDebuggingSidebarControlsPaneCss(); pauseButton = createControlButton(css.pauseButton(), DebuggerCommand.PAUSE, "Pause"); resumeButton = createControlButton(css.resumeButton(), DebuggerCommand.RESUME, "Resume"); stepOverButton = createControlButton( css.stepOverButton(), DebuggerCommand.STEP_OVER, "Step Over"); stepIntoButton = createControlButton( css.stepIntoButton(), DebuggerCommand.STEP_INTO, "Step Into"); stepOutButton = createControlButton( css.stepOutButton(), DebuggerCommand.STEP_OUT, "Step Out"); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(pauseButton); rootElement.appendChild(resumeButton); rootElement.appendChild(stepOverButton); rootElement.appendChild(stepIntoButton); rootElement.appendChild(stepOutButton); setElement(rootElement); // Hide the resume button (pause button is visible by default). CssUtils.setDisplayVisibility(resumeButton, false); } private Element createControlButton(String className, DebuggerCommand command, String tooltip) { Element button = Elements.createDivElement(className, css.buttonEnabled()); button.addEventListener(Event.CLICK, new ButtonClickListener(command), false); Tooltip.create(resources, button, PositionController.VerticalAlign.BOTTOM, PositionController.HorizontalAlign.MIDDLE, tooltip); return button; } private void setActive(boolean active) { CssUtils.setClassNameEnabled(pauseButton, css.buttonEnabled(), active); CssUtils.setClassNameEnabled(resumeButton, css.buttonEnabled(), active); } private void setPaused(boolean paused) { if (paused) { CssUtils.setDisplayVisibility(pauseButton, false); CssUtils.setDisplayVisibility(resumeButton, true); stepOverButton.addClassName(css.buttonEnabled()); stepIntoButton.addClassName(css.buttonEnabled()); stepOutButton.addClassName(css.buttonEnabled()); } else { CssUtils.setDisplayVisibility(pauseButton, true); CssUtils.setDisplayVisibility(resumeButton, false); stepOverButton.removeClassName(css.buttonEnabled()); stepIntoButton.removeClassName(css.buttonEnabled()); stepOutButton.removeClassName(css.buttonEnabled()); } } } /** * The view events. */ private interface ViewEvents { void onDebuggerCommand(DebuggerCommand command); } static DebuggingSidebarControlsPane create(View view) { return new DebuggingSidebarControlsPane(view); } private Listener delegateListener; @VisibleForTesting DebuggingSidebarControlsPane(View view) { super(view); view.setDelegate(new ViewEvents() { @Override public void onDebuggerCommand(DebuggerCommand command) { if (delegateListener != null) { delegateListener.onDebuggerCommand(command); } } }); } void setListener(Listener listener) { delegateListener = listener; } void setActive(boolean active) { getView().setActive(active); } void setPaused(boolean paused) { getView().setPaused(paused); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggerChromeApiUtils.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggerChromeApiUtils.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.ConsoleMessageLevel; import com.google.collide.client.code.debugging.DebuggerApiTypes.ConsoleMessageType; import com.google.collide.client.code.debugging.DebuggerApiTypes.CssStyleSheetHeader; 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.PropertyDescriptor; 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.client.code.debugging.DebuggerApiTypes.Scope; import com.google.collide.client.code.debugging.DebuggerApiTypes.ScopeType; import com.google.collide.client.code.debugging.DebuggerApiTypes.StackTraceItem; import com.google.collide.json.client.Jso; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonObject; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; /** * Utility class to deal with the Chrome debugger responses. */ class DebuggerChromeApiUtils { /** * Parses the {@link OnPausedResponse} debugger response. * * @param result debugger result * @return new instance, or {@code null} for invalid {@code result} */ public static OnPausedResponse parseOnPausedResponse(Jso result) { if (result == null) { return null; } final JsonArray<CallFrame> callFrames = parseCallFramesArray(result.getArrayField( "callFrames")); return new OnPausedResponse() { @Override public JsonArray<CallFrame> getCallFrames() { return callFrames; } }; } /** * Parses the {@link OnBreakpointResolvedResponse} debugger response. * * @param request original request data that was sent to the debugger * @param result debugger result * @return new instance, or {@code null} for invalid {@code result} */ public static OnBreakpointResolvedResponse parseOnBreakpointResolvedResponse(Jso request, Jso result) { if (result == null) { return null; } final JsonArray<Location> locations = parseBreakpointLocations(result); final BreakpointInfo breakpointInfo = parseBreakpointInfo(request); final String breakpointId = result.getStringField("breakpointId"); return new OnBreakpointResolvedResponse() { @Override public BreakpointInfo getBreakpointInfo() { return breakpointInfo; } @Override public String getBreakpointId() { return breakpointId; } @Override public JsonArray<Location> getLocations() { return locations; } }; } /** * Parses the debugger response that is fired when a breakpoint got removed. * * @param request original request data that was sent to the debugger * @return ID of the breakpoint that was removed */ public static String parseOnRemoveBreakpointResponse(Jso request) { if (request == null) { return null; } return request.getStringField("breakpointId"); } /** * Parses the {@link OnScriptParsedResponse} debugger response. * * @param result debugger result * @return new instance, or {@code null} for invalid {@code result} */ public static OnScriptParsedResponse parseOnScriptParsedResponse(final Jso result) { if (result == null) { return null; } return new OnScriptParsedResponse() { @Override public int getStartLine() { return result.getFieldCastedToInteger("startLine"); } @Override public int getStartColumn() { return result.getFieldCastedToInteger("startColumn"); } @Override public int getEndLine() { return result.getFieldCastedToInteger("endLine"); } @Override public int getEndColumn() { return result.getFieldCastedToInteger("endColumn"); } @Override public String getUrl() { return result.getStringField("url"); } @Override public String getScriptId() { return result.getStringField("scriptId"); } @Override public boolean isContentScript() { return result.getFieldCastedToBoolean("isContentScript"); } }; } /** * Parses the {@link OnRemoteObjectPropertiesResponse} debugger response. * * @param request original request data that was sent to the debugger * @param result debugger result * @return new instance, or {@code null} for invalid {@code request} or * {@code result} */ public static OnRemoteObjectPropertiesResponse parseOnRemoteObjectPropertiesResponse(Jso request, Jso result) { if (request == null || result == null) { return null; } final RemoteObjectId objectId = parseRemoteObjectId(request.getStringField("objectId")); final JsonArray<PropertyDescriptor> properties = parsePropertyDescriptorArray( result.getArrayField("result")); return new OnRemoteObjectPropertiesResponse() { @Override public RemoteObjectId getObjectId() { return objectId; } @Override public JsonArray<PropertyDescriptor> getProperties() { return properties; } }; } /** * Creates a {@link OnRemoteObjectPropertyChanged} debugger response for a * deleted remote object property event. * * @param remoteObjectId ID of the remote object the property was deleted from * @param propertyName name of the deleted property * @param wasThrown true if an exception was thrown by the debugger * @return new instance */ public static OnRemoteObjectPropertyChanged createOnRemoveRemoteObjectPropertyResponse( RemoteObjectId remoteObjectId, String propertyName, boolean wasThrown) { return createOnRemoteObjectPropertyChangedResponse( remoteObjectId, propertyName, null, null, false, wasThrown); } /** * Creates a {@link OnRemoteObjectPropertyChanged} debugger response for a * renamed remote object property event. * * @param remoteObjectId ID of the remote object the property was deleted from * @param oldName old property name * @param newName new property name * @param wasThrown true if an exception was thrown by the debugger * @return new instance */ public static OnRemoteObjectPropertyChanged createOnRenameRemoteObjectPropertyResponse( RemoteObjectId remoteObjectId, String oldName, String newName, boolean wasThrown) { return createOnRemoteObjectPropertyChangedResponse( remoteObjectId, oldName, newName, null, false, wasThrown); } /** * Creates a {@link OnRemoteObjectPropertyChanged} debugger response for a * edited remote object property event. * * @param remoteObjectId ID of the remote object the property was deleted from * @param propertyName name of the edited property * @param propertyValue new property value * @param wasThrown true if an exception was thrown by the debugger * @return new instance */ public static OnRemoteObjectPropertyChanged createOnEditRemoteObjectPropertyResponse( RemoteObjectId remoteObjectId, String propertyName, RemoteObject propertyValue, boolean wasThrown) { return createOnRemoteObjectPropertyChangedResponse( remoteObjectId, propertyName, propertyName, propertyValue, true, wasThrown); } private static OnRemoteObjectPropertyChanged createOnRemoteObjectPropertyChangedResponse( final RemoteObjectId remoteObjectId, final String oldName, final String newName, final RemoteObject value, final boolean isValueChanged, final boolean wasThrown) { return new OnRemoteObjectPropertyChanged() { @Override public RemoteObjectId getObjectId() { return remoteObjectId; } @Override public String getOldName() { return oldName; } @Override public String getNewName() { return newName; } @Override public boolean isValueChanged() { return isValueChanged; } @Override public RemoteObject getValue() { return value; } @Override public boolean wasThrown() { return wasThrown; } }; } /** * Parses the {@link OnEvaluateExpressionResponse} debugger response. * * @param request original request data that was sent to the debugger * @param result debugger result * @return new instance, or {@code null} for invalid {@code request} or * {@code result} */ public static OnEvaluateExpressionResponse parseOnEvaluateExpressionResponse(Jso request, Jso result) { if (request == null || result == null) { return null; } final String expression = request.getStringField("expression"); final String callFrameId = request.getStringField("callFrameId"); final RemoteObject evaluationResult = parseRemoteObject((Jso) result.getObjectField("result")); final boolean wasThrown = result.getFieldCastedToBoolean("wasThrown"); return new OnEvaluateExpressionResponse() { @Override public String getExpression() { return expression; } @Override public String getCallFrameId() { return callFrameId; } @Override public RemoteObject getResult() { return evaluationResult; } @Override public boolean wasThrown() { return wasThrown; } }; } /** * Parses the {@link OnAllCssStyleSheetsResponse} debugger response. * * @param result debugger result * @return new instance, or {@code null} for invalid {@code result} */ public static OnAllCssStyleSheetsResponse parseOnAllCssStyleSheetsResponse(Jso result) { if (result == null) { return null; } final JsonArray<CssStyleSheetHeader> headers = parseCssStyleSheetHeaders( result.getArrayField("headers")); return new OnAllCssStyleSheetsResponse() { @Override public JsonArray<CssStyleSheetHeader> getHeaders() { return headers; } }; } /** * Parses the {@link DebuggerChromeApi#METHOD_RUNTIME_CALL_FUNCTION_ON} * debugger response. * * @param result debugger result * @return new instance, or {@code null} for invalid {@code result} */ public static RemoteObject parseCallFunctionOnResult(Jso result) { if (result == null) { return null; } return parseRemoteObject((Jso) result.getObjectField("result")); } /** * Parses the {@link ConsoleMessage} debugger response. * * @param result debugger result * @return new instance, or {@code null} for invalid {@code result} */ public static ConsoleMessage parseOnConsoleMessageReceived(Jso result) { if (result == null) { return null; } Jso json = (Jso) result.getObjectField("message"); final int lineNumber = json.hasOwnProperty("line") ? json.getFieldCastedToInteger("line") : -1; final int repeatCount = json.hasOwnProperty("repeatCount") ? json.getFieldCastedToInteger("repeatCount") : 1; final ConsoleMessageLevel messageLevel = parseConsoleMessageLevel(json.getStringField("level")); final ConsoleMessageType messageType = parseConsoleMessageType(json.getStringField("type")); final JsonArray<RemoteObject> parameters = parseRemoteObjectArray( json.getArrayField("parameters")); final JsonArray<StackTraceItem> stackTrace = parseStackTraceItemArray( json.getArrayField("stackTrace")); final String text = json.getStringField("text"); final String url = json.getStringField("url"); return new ConsoleMessage() { @Override public ConsoleMessageLevel getLevel() { return messageLevel; } @Override public ConsoleMessageType getType() { return messageType; } @Override public int getLineNumber() { return lineNumber; } @Override public JsonArray<RemoteObject> getParameters() { return parameters; } @Override public int getRepeatCount() { return repeatCount; } @Override public JsonArray<StackTraceItem> getStackTrace() { return stackTrace; } @Override public String getText() { return text; } @Override public String getUrl() { return url; } }; } /** * Parses the debugger response that is fired when subsequent console * message(s) are equal to the previous one(s). * * @param result debugger result * @return new repeat count value, or {@code -1} for invalid {@code result} */ public static int parseOnConsoleMessageRepeatCountUpdated(Jso result) { if (result == null) { return -1; } return result.getFieldCastedToInteger("count"); } private static JsonArray<PropertyDescriptor> parsePropertyDescriptorArray( JsonArray<JsonObject> jsonArray) { JsonArray<PropertyDescriptor> result = JsonCollections.createArray(); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { PropertyDescriptor propertyDescriptor = parsePropertyDescriptor((Jso) jsonArray.get(i)); if (propertyDescriptor != null) { result.add(propertyDescriptor); } } } return result; } private static PropertyDescriptor parsePropertyDescriptor(final Jso json) { if (json == null) { return null; } final RemoteObject remoteObject = parseRemoteObject((Jso) json.getObjectField("value")); final RemoteObject getter = parseRemoteObject((Jso) json.getObjectField("get")); final RemoteObject setter = parseRemoteObject((Jso) json.getObjectField("set")); return new PropertyDescriptor() { @Override public String getName() { return json.getStringField("name"); } @Override public RemoteObject getValue() { return remoteObject; } @Override public boolean wasThrown() { return json.getFieldCastedToBoolean("wasThrown"); } @Override public boolean isConfigurable() { return json.getFieldCastedToBoolean("configurable"); } @Override public boolean isEnumerable() { return json.getFieldCastedToBoolean("enumerable"); } @Override public boolean isWritable() { return json.getFieldCastedToBoolean("writable"); } @Override public RemoteObject getGetterFunction() { return getter; } @Override public RemoteObject getSetterFunction() { return setter; } }; } private static JsonArray<CallFrame> parseCallFramesArray(JsonArray<JsonObject> jsonArray) { JsonArray<CallFrame> result = JsonCollections.createArray(); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { CallFrame callFrame = parseCallFrame((Jso) jsonArray.get(i)); if (callFrame != null) { result.add(callFrame); } } } return result; } private static CallFrame parseCallFrame(Jso json) { if (json == null) { return null; } final String functionName = json.getStringField("functionName"); final String callFrameId = json.getStringField("callFrameId"); final Location location = parseLocation((Jso) json.getObjectField("location")); final JsonArray<Scope> scopeChain = parseScopeChain(json.getArrayField("scopeChain")); final RemoteObject thisObject = parseRemoteObject((Jso) json.getObjectField("this")); return new CallFrame() { @Override public String getFunctionName() { return functionName; } @Override public String getId() { return callFrameId; } @Override public Location getLocation() { return location; } @Override public JsonArray<Scope> getScopeChain() { return scopeChain; } @Override public RemoteObject getThis() { return thisObject; } }; } private static Location parseLocation(final Jso json) { if (json == null) { return null; } return new Location() { @Override public int getColumnNumber() { return json.getFieldCastedToInteger("columnNumber"); } @Override public int getLineNumber() { return json.getFieldCastedToInteger("lineNumber"); } @Override public String getScriptId() { return json.getStringField("scriptId"); } }; } private static JsonArray<Scope> parseScopeChain(JsonArray<JsonObject> jsonArray) { JsonArray<Scope> result = JsonCollections.createArray(); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { Scope scope = parseScope(jsonArray.get(i)); if (scope != null) { result.add(scope); } } } return result; } private static Scope parseScope(JsonObject json) { if (json == null) { return null; } final RemoteObject object = parseRemoteObject((Jso) json.getObjectField("object")); final ScopeType scopeType = parseScopeType(json.getStringField("type")); return new Scope() { @Override public RemoteObject getObject() { return object; } @Override public boolean isTransient() { // @see http://code.google.com/chrome/devtools/docs/protocol/tot/debugger.html#type-Scope // For GLOBAL and WITH scopes it represents the actual object; for the rest of the scopes, // it is artificial transient object enumerating scope variables as its properties. return scopeType != ScopeType.GLOBAL && scopeType != ScopeType.WITH; } @Override public ScopeType getType() { return scopeType; } }; } private static ScopeType parseScopeType(String type) { return type == null ? null : ScopeType.valueOf(type.toUpperCase()); } private static JsonArray<RemoteObject> parseRemoteObjectArray(JsonArray<JsonObject> jsonArray) { JsonArray<RemoteObject> result = JsonCollections.createArray(); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { RemoteObject remoteObject = parseRemoteObject((Jso) jsonArray.get(i)); if (remoteObject != null) { result.add(remoteObject); } } } return result; } private static RemoteObject parseRemoteObject(Jso json) { if (json == null) { return null; } final RemoteObjectId objectId = parseRemoteObjectId(json.getStringField("objectId")); final RemoteObjectType remoteObjectType = parseRemoteObjectType(json.getStringField("type")); final RemoteObjectSubType remoteObjectSubType = parseRemoteObjectSubType( json.getStringField("subtype")); final String description = StringUtils.ensureNotEmpty(json.getStringField("description"), json.getFieldCastedToString("value")); return new RemoteObject() { @Override public String getDescription() { return description; } @Override public boolean hasChildren() { return objectId != null; } @Override public RemoteObjectId getObjectId() { return objectId; } @Override public RemoteObjectType getType() { return remoteObjectType; } @Override public RemoteObjectSubType getSubType() { return remoteObjectSubType; } }; } private static RemoteObjectType parseRemoteObjectType(String type) { return type == null ? null : RemoteObjectType.valueOf(type.toUpperCase()); } private static RemoteObjectSubType parseRemoteObjectSubType(String subtype) { return subtype == null ? null : RemoteObjectSubType.valueOf(subtype.toUpperCase()); } private static RemoteObjectId parseRemoteObjectId(final String objectId) { if (StringUtils.isNullOrEmpty(objectId)) { return null; } return new RemoteObjectId() { @Override public String toString() { return objectId; } }; } /** * Handles both "Debugger.setBreakpointByUrl" and "Debugger.breakpointResolved" responses. * * Docs: * http://code.google.com/chrome/devtools/docs/protocol/tot/debugger.html#command-setBreakpointByUrl * http://code.google.com/chrome/devtools/docs/protocol/tot/debugger.html#event-breakpointResolved */ private static JsonArray<Location> parseBreakpointLocations(Jso json) { JsonArray<Location> result = JsonCollections.createArray(); if (json != null) { // Debugger.breakpointResolved response. Location location = parseLocation((Jso) json.getObjectField("location")); if (location != null) { result.add(location); } // Debugger.setBreakpointByUrl response. JsonArray<JsonObject> jsonArray = json.getArrayField("locations"); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { location = parseLocation((Jso) jsonArray.get(i)); if (location != null) { result.add(location); } } } } return result; } private static BreakpointInfo parseBreakpointInfo(final Jso json) { if (json == null) { return null; } return new BreakpointInfo() { @Override public String getUrl() { return json.getStringField("url"); } @Override public String getUrlRegex() { return json.getStringField("urlRegex"); } @Override public int getLineNumber() { return json.getFieldCastedToInteger("lineNumber"); } @Override public int getColumnNumber() { return json.getFieldCastedToInteger("columnNumber"); } @Override public String getCondition() { return json.getStringField("condition"); } }; } private static JsonArray<CssStyleSheetHeader> parseCssStyleSheetHeaders( JsonArray<JsonObject> jsonArray) { JsonArray<CssStyleSheetHeader> result = JsonCollections.createArray(); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { CssStyleSheetHeader header = parseCssStyleSheetHeader((Jso) jsonArray.get(i)); if (header != null) { result.add(header); } } } return result; } private static CssStyleSheetHeader parseCssStyleSheetHeader(final Jso json) { if (json == null) { return null; } return new CssStyleSheetHeader() { @Override public boolean isDisabled() { return json.getFieldCastedToBoolean("disabled"); } @Override public String getId() { return json.getStringField("styleSheetId"); } @Override public String getUrl() { return json.getStringField("sourceURL"); } @Override public String getTitle() { return json.getStringField("title"); } }; } private static ConsoleMessageLevel parseConsoleMessageLevel(String level) { return level == null ? null : ConsoleMessageLevel.valueOf(level.toUpperCase()); } private static ConsoleMessageType parseConsoleMessageType(String type) { return type == null ? null : ConsoleMessageType.valueOf(type.toUpperCase()); } private static JsonArray<StackTraceItem> parseStackTraceItemArray( JsonArray<JsonObject> jsonArray) { JsonArray<StackTraceItem> result = JsonCollections.createArray(); if (jsonArray != null) { for (int i = 0, n = jsonArray.size(); i < n; ++i) { StackTraceItem item = parseStackTraceItem((Jso) jsonArray.get(i)); if (item != null) { result.add(item); } } } return result; } private static StackTraceItem parseStackTraceItem(final Jso json) { if (json == null) { return null; } return new StackTraceItem() { @Override public int getColumnNumber() { return json.getFieldCastedToInteger("columnNumber"); } @Override public String getFunctionName() { return json.getStringField("functionName"); } @Override public int getLineNumber() { return json.getFieldCastedToInteger("lineNumber"); } @Override public String getUrl() { return json.getStringField("url"); } }; } private DebuggerChromeApiUtils() {} // COV_NF_LINE }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggerApi.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggerApi.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.CssStyleSheetHeader; 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; /** * Defines an API to communicate with the browser debugger. * * <p>This API allows to arrange multiple debugging sessions simultaneously. * Each debugging session is identified by its session ID. For example, we may * provide a workspace ID as a debugging session ID, so that debugging requests * from different IDE instances (browser tabs) should go to the same debuggee * instance. Otherwise, debugging session IDs may be unique across different * workspaces and/or different IDE instances. */ interface DebuggerApi { /** * @return true if the debugger is available */ public boolean isDebuggerAvailable(); /** * @return URL of the browser extension that provides the debugging API, * or {@code null} if no such extension is available */ public String getDebuggingExtensionUrl(); /** * Runs the debugger on a given URL. This may open a new window or tab to run * the debugger. * * @param sessionId ID of the debugging session * @param url URL to run the debugger on */ public void runDebugger(String sessionId, String url); /** * Shuts down a given debugger session. This may close the corresponding * debuggee window or tab. * * <p>To reestablish the debugging session, just call the * {@link #runDebugger} again. * * @param sessionId ID of the debugging session */ public void shutdownDebugger(String sessionId); /** * Sets a JavaScript breakpoint at a given location. * * @param sessionId ID of the debugging session * @param breakpointInfo breakpoint data */ public void setBreakpointByUrl(String sessionId, BreakpointInfo breakpointInfo); /** * Removes a JavaScript breakpoint by the resolved breakpoint ID, that comes * from the {@link DebuggerResponseListener#onBreakpointResolved} event. * * @param sessionId ID of the debugging session * @param breakpointId ID of the breakpoint to remove */ public void removeBreakpoint(String sessionId, String breakpointId); /** * Activates/deactivates all breakpoints on the debuggee page. * * @param sessionId ID of the debugging session * @param active new value for breakpoints active state */ public void setBreakpointsActive(String sessionId, boolean active); /** * Defines pause on exceptions state. Can be set to stop on all exceptions, * uncaught exceptions or no exceptions. * * @param sessionId ID of the debugging session * @param state pause on exceptions state */ public void setPauseOnExceptions(String sessionId, PauseOnExceptionsState state); /** * Stops debugger on the next JavaScript statement. * * @param sessionId ID of the debugging session */ public void pause(String sessionId); /** * Resumes debugger execution. * * @param sessionId ID of the debugging session */ public void resume(String sessionId); /** * Steps debugger into the statement. * * @param sessionId ID of the debugging session */ public void stepInto(String sessionId); /** * Steps debugger out of the function. * * @param sessionId ID of the debugging session */ public void stepOut(String sessionId); /** * Steps debugger over the statement. * * @param sessionId ID of the debugging session */ public void stepOver(String sessionId); /** * Requests properties of a given {@link RemoteObject}. * * <p>This will request only properties in the object's prototype (in terms * of the {@code hasOwnProperty} method). * * @param sessionId ID of the debugging session * @param remoteObjectId ID of the remote object to request the properties for */ public void requestRemoteObjectProperties(String sessionId, RemoteObjectId remoteObjectId); /** * Sets the property with a given name in a given {@link RemoteObject} * equal to a given expression, evaluated on the global object. * * @param sessionId ID of the debugging session * @param remoteObjectId ID of the remote object to set the property on * @param propertyName property name to set the value for * @param propertyValueExpression expression to evaluate and set as the value * @see #evaluateExpression */ public void setRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression); /** * Sets the property with a given name in a given {@link RemoteObject} * equal to a given expression, evaluated on a given call frame. * * @param sessionId ID of the debugging session * @param callFrame the call frame to evaluate on. This is a part of the * {@link DebuggerResponseListener#onPaused} response * @param remoteObjectId ID of the remote object to set the property on * @param propertyName property name to set the value for * @param propertyValueExpression expression to evaluate and set as the value * @see #evaluateExpressionOnCallFrame */ public void setRemoteObjectPropertyEvaluatedOnCallFrame(String sessionId, CallFrame callFrame, RemoteObjectId remoteObjectId, String propertyName, String propertyValueExpression); /** * Removes a property with the given name from the given {@link RemoteObject}. * * @param sessionId ID of the debugging session * @param remoteObjectId ID of the remote object to set the property on * @param propertyName property name to remove */ public void removeRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String propertyName); /** * Renames a given property within a {@link RemoteObject}. * * @param sessionId ID of the debugging session * @param remoteObjectId ID of the remote object to rename the property for * @param oldName old property name * @param newName new property name */ public void renameRemoteObjectProperty(String sessionId, RemoteObjectId remoteObjectId, String oldName, String newName); /** * Evaluates a given expression on the global object. * * <p>Note: The evaluation result is valid until the * {@link DebuggerResponseListener#onGlobalObjectChanged} is fired. * * @param sessionId ID of the debugging session * @param expression expression to evaluate */ public void evaluateExpression(String sessionId, String expression); /** * Evaluates expression on a given call frame. * * <p>API design notes: a {@link CallFrame} type was chosen as an argument * instead of a {@link String} {@code callFrameId}, so that to give extra * flexibility to the implementers of this interface, as some APIs may only * support evaluation on a given {@link RemoteObject}. In this case, the * {@code callFrame} object should provide all the necessary information. * * @param sessionId ID of the debugging session * @param callFrame the call frame to evaluate on. This is a part of the * {@link DebuggerResponseListener#onPaused} response * @param expression expression to evaluate */ public void evaluateExpressionOnCallFrame(String sessionId, CallFrame callFrame, String expression); /** * Requests {@link CssStyleSheetHeader} entries for all known stylesheets. * * @param sessionId ID of the debugging session */ public void requestAllCssStyleSheets(String sessionId); /** * Sets the new text for a given stylesheet. * * @param sessionId ID of the debugging session * @param styleSheetId ID of the stylesheet to modify * @param text the text to set as CSS rules */ public void setStyleSheetText(String sessionId, String styleSheetId, String text); /** * Sends a custom raw message to the debugger. * * @param sessionId ID of the debugging session * @param message raw message to send to the debugger */ public void sendCustomMessage(String sessionId, String message); /** * Adds a given {@link DebuggerResponseListener}. * * @param debuggerResponseListener the listener to add */ public void addDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener); /** * Removes a given {@link DebuggerResponseListener}. * * @param debuggerResponseListener the listener to remove */ public void removeDebuggerResponseListener(DebuggerResponseListener debuggerResponseListener); /** * Defines an API of the debugger responses. */ public interface DebuggerResponseListener { /** * Fired when debugger becomes available or unavailable. * * <p>To find out the most recent debugger state call the * {@link #isDebuggerAvailable} method. */ public void onDebuggerAvailableChanged(); /** * Fired when debugger is attached to the debuggee application. * * @param sessionId ID of the debugging session */ public void onDebuggerAttached(String sessionId); /** * Fired when debugger is detached from the debuggee application. * * <p>This may happen, for example, if the debuggee application was * terminated, or the browser extension providing the debugging API was * disabled, or for any other reason. * * @param sessionId ID of the debugging session */ public void onDebuggerDetached(String sessionId); /** * Fired when a breakpoint is resolved by the debugger. * * <p>This event may be fired several times for a single breakpoint as long * as any new information becomes available to the debugger. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onBreakpointResolved(String sessionId, OnBreakpointResolvedResponse response); /** * Fired when a breakpoint is removed by the debugger. * * @param sessionId ID of the debugging session * @param breakpointId ID of the breakpoint that got removed */ public void onBreakpointRemoved(String sessionId, String breakpointId); /** * Fired when debugger stops on a breakpoint or exception, or because of * any other stop criteria. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onPaused(String sessionId, OnPausedResponse response); /** * Fired when debugger resumes execution. * * @param sessionId ID of the debugging session */ public void onResumed(String sessionId); /** * Fired when debugger parses a script. This event is also fired for all * known scripts upon enabling debugger. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onScriptParsed(String sessionId, OnScriptParsedResponse response); /** * Fired as a response to the {@link #requestRemoteObjectProperties} method * call. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onRemoteObjectPropertiesResponse(String sessionId, OnRemoteObjectPropertiesResponse response); /** * Fired when a property of a {@link RemoteObject} was was edited, renamed * or deleted. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onRemoteObjectPropertyChanged(String sessionId, OnRemoteObjectPropertyChanged response); /** * Fired as a response to the {@link #evaluateExpressionOnCallFrame} method * call. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onEvaluateExpressionResponse(String sessionId, OnEvaluateExpressionResponse response); /** * Fired when a remote global object (global scope) has changed. This is to * notify that all expressions evaluated on the global object are no longer * valid, and should be refreshed. * * @param sessionId ID of the debugging session */ public void onGlobalObjectChanged(String sessionId); /** * Fired as a response to the {@link #requestAllCssStyleSheets} method call. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onAllCssStyleSheetsResponse(String sessionId, OnAllCssStyleSheetsResponse response); /** * Fired when a console message is received from the debugger. * * @param sessionId ID of the debugging session * @param message console message */ public void onConsoleMessage(String sessionId, ConsoleMessage message); /** * Fired when subsequent console message(s) are equal to the previous * one(s). * * @param sessionId ID of the debugging session * @param repeatCount new repeat count value */ public void onConsoleMessageRepeatCountUpdated(String sessionId, int repeatCount); /** * Fired when all console messages should be cleared. This happens either * upon manual {@code clearMessages} command or after a page navigation. * * @param sessionId ID of the debugging session */ public void onConsoleMessagesCleared(String sessionId); /** * Response for a custom message sent via the {@link #sendCustomMessage}. * * @param sessionId ID of the debugging session * @param response debugger response */ public void onCustomMessageResponse(String sessionId, String response); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggingModelRenderer.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingModelRenderer.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.CallFrame; import com.google.collide.client.code.debugging.DebuggerApiTypes.Location; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnPausedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnScriptParsedResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.code.debugging.DebuggerApiTypes.Scope; import com.google.collide.client.editor.Editor; import com.google.collide.client.testing.DebugAttributeSetter; import com.google.collide.client.util.JsIntegerMap; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.StringUtils; import com.google.common.base.Preconditions; 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.css.CSSStyleDeclaration; import elemental.dom.Element; /** * A renderer for the debugging model. */ public class DebuggingModelRenderer { /** * CssResource for the debugging model UI. */ public interface Css extends CssResource { String breakpoint(); String breakpointInactive(); String executionLine(); String gutterExecutionLine(); } /** * ClientBundle for the debugging model UI. */ public interface Resources extends ClientBundle { @Source({"DebuggingModelRenderer.css", "com/google/collide/client/editor/constants.css"}) Css workspaceEditorDebuggingModelCss(); @Source("gutterExecutionLine.png") ImageResource gutterExecutionLine(); @Source("breakpointGutterActive.png") DataResource breakpointGutterActiveResource(); @Source("breakpointGutterInactive.png") DataResource breakpointGutterInactiveResource(); } public static DebuggingModelRenderer create(DebuggingModelRenderer.Resources resources, Editor editor, DebuggingSidebar debuggingSidebar, DebuggerState debuggerState) { return new DebuggingModelRenderer(resources, editor, debuggingSidebar, debuggerState); } private final Css css; private final Editor editor; private final DebuggingSidebar debuggingSidebar; private final DebuggerState debuggerState; private JsIntegerMap<Element> lineNumberToElementCache = JsIntegerMap.create(); private AnchoredExecutionLine anchoredExecutionLine; private DebuggingModelRenderer(DebuggingModelRenderer.Resources resources, Editor editor, DebuggingSidebar debuggingSidebar, DebuggerState debuggerState) { this.css = resources.workspaceEditorDebuggingModelCss(); this.editor = editor; this.debuggingSidebar = debuggingSidebar; this.debuggerState = debuggerState; } void renderBreakpointOnGutter(int lineNumber, boolean active) { Element element = lineNumberToElementCache.get(lineNumber); if (element == null) { element = Elements.createDivElement(css.breakpoint()); element.getStyle().setTop(editor.getBuffer().calculateLineTop(lineNumber), CSSStyleDeclaration.Unit.PX); new DebugAttributeSetter().add("linenumber", String.valueOf(lineNumber + 1)).on(element); editor.getLeftGutter().addUnmanagedElement(element); lineNumberToElementCache.put(lineNumber, element); } CssUtils.setClassNameEnabled(element, css.breakpointInactive(), !active); } void removeBreakpointOnGutter(int lineNumber) { Element element = lineNumberToElementCache.get(lineNumber); if (element != null) { editor.getLeftGutter().removeUnmanagedElement(element); lineNumberToElementCache.erase(lineNumber); } } void renderDebuggerState() { debuggingSidebar.setActive(debuggerState.isActive()); debuggingSidebar.setPaused(debuggerState.isPaused()); debuggingSidebar.clearCallStack(); if (debuggerState.isPaused()) { OnPausedResponse onPausedResponse = Preconditions.checkNotNull( debuggerState.getOnPausedResponse()); JsonArray<CallFrame> callFrames = onPausedResponse.getCallFrames(); for (int i = 0, n = callFrames.size(); i < n; ++i) { CallFrame callFrame = callFrames.get(i); Location location = callFrame.getLocation(); OnScriptParsedResponse onScriptParsedResponse = debuggerState.getOnScriptParsedResponse( location.getScriptId()); // TODO: What about i18n? String title = StringUtils.ensureNotEmpty(callFrame.getFunctionName(), "(anonymous function)"); String subtitle = getShortenedScriptUrl(onScriptParsedResponse) + ":" + (location.getLineNumber() + 1); debuggingSidebar.addCallFrame(title, subtitle); } } } void renderDebuggerCallFrame() { CallFrame callFrame = debuggerState.getActiveCallFrame(); if (callFrame == null) { // Debugger is not paused. Remove the previous scope tree UI. debuggingSidebar.setScopeVariablesRootNodes(null); debuggingSidebar.refreshWatchExpressions(); return; } // Render the Scope Variables pane. JsonArray<RemoteObjectNode> rootNodes = JsonCollections.createArray(); JsonArray<Scope> scopeChain = callFrame.getScopeChain(); for (int i = 0, n = scopeChain.size(); i < n; ++i) { Scope scope = scopeChain.get(i); String name = StringUtils.capitalizeFirstLetter(scope.getType().toString()); RemoteObject remoteObject = scope.getObject(); RemoteObjectNode.Builder scopeNodeBuilder = new RemoteObjectNode.Builder(name, remoteObject) .setOrderIndex(i) .setWritable(false) .setDeletable(false) .setTransient(scope.isTransient()); // Append the call frame "this" object to the top scope. if (i == 0 && callFrame.getThis() != null) { RemoteObjectNode thisNode = new RemoteObjectNode.Builder("this", callFrame.getThis()) .setWritable(false) .setDeletable(false) .build(); RemoteObjectNode scopeNode = scopeNodeBuilder .setHasChildren(true) // At least will contain the "this" child. .build(); scopeNode.addChild(thisNode); rootNodes.add(scopeNode); } else { rootNodes.add(scopeNodeBuilder.build()); } } debuggingSidebar.setScopeVariablesRootNodes(rootNodes); debuggingSidebar.refreshWatchExpressions(); } void renderExecutionLine(int lineNumber) { removeExecutionLine(); anchoredExecutionLine = AnchoredExecutionLine.create(editor, lineNumber, css.executionLine(), css.gutterExecutionLine()); } void removeExecutionLine() { if (anchoredExecutionLine != null) { anchoredExecutionLine.teardown(); anchoredExecutionLine = null; } } private static String getShortenedScriptUrl(OnScriptParsedResponse onScriptParsedResponse) { String url = onScriptParsedResponse != null ? onScriptParsedResponse.getUrl() : null; if (StringUtils.isNullOrEmpty(url)) { // TODO: What about i18n? return "unknown"; } if (onScriptParsedResponse.isContentScript()) { return url; // No shortening. } while (url.endsWith("/")) { url = url.substring(0, url.length() - 1); } int pos = url.lastIndexOf("/"); if (pos >= 0) { return url.substring(pos + 1); } return url; } void handleDocumentChanged() { lineNumberToElementCache = JsIntegerMap.create(); removeExecutionLine(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/StaticSourceMapping.java
client/src/main/java/com/google/collide/client/code/debugging/StaticSourceMapping.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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; import com.google.collide.shared.util.RegExpUtils; import com.google.common.base.Preconditions; /** * Identity source mapping to be used for static files. * */ public class StaticSourceMapping implements SourceMapping { private final String resourceBaseUri; public static StaticSourceMapping create(String baseUri) { Preconditions.checkNotNull(baseUri, "Base URI is NULL!"); return new StaticSourceMapping(baseUri); } private StaticSourceMapping(String resourceBaseUri) { this.resourceBaseUri = ensureNoTrailingSlash(resourceBaseUri).toLowerCase(); } @Override public PathUtil getLocalScriptPath(@Nullable OnScriptParsedResponse response) { if (response == null) { return null; } return getLocalSourcePath(response.getUrl()); } @Override public int getLocalSourceLineNumber(@Nullable OnScriptParsedResponse response, Location location) { return location.getLineNumber(); } @Override public BreakpointInfo getRemoteBreakpoint(Breakpoint breakpoint) { String url = getRemoteSourceUri(breakpoint.getPath()); // We allow arbitrary query and anchor parts in the breakpoint URLs for // static resources. String urlRegex = "^" + RegExpUtils.escape(url) + "([?#].*)?$"; return new BreakpointInfoImpl(urlRegex, breakpoint.getLineNumber(), 0, breakpoint.getCondition()); } @Override public PathUtil getLocalSourcePath(String resourceUri) { Preconditions.checkNotNull(resourceBaseUri, "Base URI is NULL! Impossible?!"); // TODO: stopgap to get more // stable build to rehearse his demo with. Suggest tracking down actual // source of why resourceBaseUri could be null. if (resourceUri == null || resourceBaseUri == null) { return null; } if (resourceUri.toLowerCase().startsWith(resourceBaseUri)) { String relativePath = resourceUri.substring(resourceBaseUri.length()); // We drop any query and anchor part, since we assume this is a static // resource. int pos = relativePath.indexOf('?'); if (pos != -1) { relativePath = relativePath.substring(0, pos); } pos = relativePath.indexOf('#'); if (pos != -1) { relativePath = relativePath.substring(0, pos); } return new PathUtil(relativePath); } return null; } @Override public String getRemoteSourceUri(PathUtil path) { return resourceBaseUri + path.getPathString(); } private static String ensureNoTrailingSlash(String path) { while (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } return path; } private static class BreakpointInfoImpl implements BreakpointInfo { private final String urlRegex; private final int lineNumber; private final int columnNumber; private final String condition; private BreakpointInfoImpl( String urlRegex, int lineNumber, int columnNumber, String condition) { this.urlRegex = urlRegex; this.lineNumber = lineNumber; this.columnNumber = columnNumber; this.condition = condition; } @Override public String getUrl() { return null; // urlRegex will be used instead. } @Override public String getUrlRegex() { return urlRegex; } @Override public int getLineNumber() { return lineNumber; } @Override public int getColumnNumber() { return columnNumber; } @Override public String getCondition() { return condition; } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggingSidebarNoApiPane.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarNoApiPane.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 collide.client.util.Elements; import com.google.collide.client.util.AnimationUtils; import com.google.collide.client.util.dom.DomUtils; import com.google.collide.mvp.CompositeView; import com.google.collide.mvp.UiComponent; 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.ImageResource; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; import elemental.html.AnchorElement; import elemental.html.DivElement; /** * Debugging sidebar pane that is shown when no {@link DebuggerApi} is * available. */ public class DebuggingSidebarNoApiPane extends UiComponent<DebuggingSidebarNoApiPane.View> { public interface Css extends CssResource { String root(); String headerLogo(); String headerText(); String button(); String footerText(); } interface Resources extends ClientBundle { @Source("DebuggingSidebarNoApiPane.css") Css workspaceEditorDebuggingSidebarNoApiPaneCss(); @Source("extensionPackage.png") ImageResource extensionPackage(); } /** * Listener of this pane's events. */ interface Listener { void onShouldDisplayNoApiPaneChange(); } private static class Panel { private final Element root; private final AnchorElement button; private final DivElement footer; private Panel(Element root, AnchorElement button, DivElement footer) { this.root = root; this.button = button; this.footer = footer; } } /** * The view for the sidebar call stack pane. */ static class View extends CompositeView<Void> { private final Css css; private final Panel downloadExtension; private final Panel browserNotSupported; View(Resources resources) { css = resources.workspaceEditorDebuggingSidebarNoApiPaneCss(); downloadExtension = createLayout("", "Download Debugging Extension", "Install the Debugging Extension to support debugging in Collide."); browserNotSupported = createLayout( "Your browser does not support breakpoint debugging in Collide.", "Download Google Chrome", "It's free and installs in seconds."); setElement(Elements.createDivElement()); } private Panel createLayout(String headerText, String buttonText, String footerText) { Element root = Elements.createDivElement(css.root()); if (StringUtils.isNullOrEmpty(headerText)) { root.appendChild(Elements.createDivElement(css.headerLogo())); } else { DomUtils.appendDivWithTextContent(root, css.headerText(), headerText); } AnchorElement button = Elements.createAnchorElement(); button.setClassName(css.button()); button.setTextContent(buttonText); root.appendChild(button); DivElement footer = DomUtils.appendDivWithTextContent(root, css.footerText(), footerText); return new Panel(root, button, footer); } private void showLayout(@Nullable String extensionUrl) { hideLayout(); boolean isExtensionSupported = (extensionUrl != null); final Panel panel = isExtensionSupported ? downloadExtension : browserNotSupported; getElement().appendChild(panel.root); panel.button.setTarget(StringUtils.isNullOrEmpty(extensionUrl) ? "_blank" : ""); // TODO: What's the right answer? panel.button.setHref(StringUtils.ensureNotEmpty(extensionUrl, "http://www.google.com/url?sa=D&q=http://www.google.com/chrome/")); if (isExtensionSupported) { panel.button.addEventListener(Event.CLICK, new EventListener() { @Override public void handleEvent(Event evt) { panel.footer.getStyle().setColor("#000"); panel.footer.getStyle().setOpacity(0.0); panel.footer.setTextContent("Please accept extension in download bar," + " confirm installation, and then reload the page."); AnimationUtils.animatePropertySet( panel.footer, "opacity", "1.0", AnimationUtils.LONG_TRANSITION_DURATION); } }, false); } } private void hideLayout() { downloadExtension.root.removeFromParent(); browserNotSupported.root.removeFromParent(); } } static DebuggingSidebarNoApiPane create(View view, DebuggerState debuggerState) { return new DebuggingSidebarNoApiPane(view, debuggerState); } private final DebuggerState debuggerState; private Listener delegateListener; private final DebuggerState.DebuggerAvailableListener debuggerAvailableListener = new DebuggerState.DebuggerAvailableListener() { @Override public void onDebuggerAvailableChange() { displayOrHide(); if (delegateListener != null) { delegateListener.onShouldDisplayNoApiPaneChange(); } } }; @VisibleForTesting DebuggingSidebarNoApiPane(View view, DebuggerState debuggerState) { super(view); this.debuggerState = debuggerState; debuggerState.getDebuggerAvailableListenerRegistrar().add(debuggerAvailableListener); displayOrHide(); } void setListener(Listener listener) { delegateListener = listener; } boolean shouldDisplay() { return !debuggerState.isDebuggerAvailable(); } private void displayOrHide() { if (shouldDisplay()) { getView().showLayout(debuggerState.getDebuggingExtensionUrl()); } else { getView().hideLayout(); } } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggingSidebarCallStackPane.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarCallStackPane.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.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; import elemental.events.Event; import elemental.events.EventListener; /** * Debugging sidebar call stack pane. * */ public class DebuggingSidebarCallStackPane extends UiComponent<DebuggingSidebarCallStackPane.View> { public interface Css extends CssResource { String root(); String callFrame(); String callFrameTitle(); String callFrameSubTitle(); String callFrameSelected(); } interface Resources extends ClientBundle { @Source("DebuggingSidebarCallStackPane.css") Css workspaceEditorDebuggingSidebarCallStackPaneCss(); } /** * Listener of this pane's events. */ interface Listener { void onCallFrameSelect(int depth); } /** * The view for the sidebar call stack pane. */ static class View extends CompositeView<ViewEvents> { private final Css css; private final EventListener clickListener = new EventListener() { @Override public void handleEvent(Event evt) { Element callFrame = CssUtils.getAncestorOrSelfWithClassName((Element) evt.getTarget(), css.callFrame()); if (callFrame != null) { onCallFrameClick(callFrame); } } }; View(Resources resources) { css = resources.workspaceEditorDebuggingSidebarCallStackPaneCss(); Element rootElement = Elements.createDivElement(css.root()); rootElement.addEventListener(Event.CLICK, clickListener, false); setElement(rootElement); } private void addCallFrame(String title, String subtitle) { boolean addingFirstElement = !getElement().hasChildNodes(); Element callFrame = Elements.createDivElement(css.callFrame()); DomUtils.appendDivWithTextContent(callFrame, css.callFrameSubTitle(), subtitle); DomUtils.appendDivWithTextContent(callFrame, css.callFrameTitle(), title); getElement().appendChild(callFrame); if (addingFirstElement) { callFrame.addClassName(css.callFrameSelected()); } } private void clearCallStack() { getElement().setInnerHTML(""); } private void onCallFrameClick(Element callFrame) { Element selected = DomUtils.getFirstElementByClassName(getElement(), css.callFrameSelected()); if (selected != null) { selected.removeClassName(css.callFrameSelected()); } callFrame.addClassName(css.callFrameSelected()); int index = DomUtils.getSiblingIndexWithClassName(callFrame, css.callFrame()); getDelegate().onCallFrameSelect(index); } } /** * The view events. */ private interface ViewEvents { void onCallFrameSelect(int depth); } static DebuggingSidebarCallStackPane create(View view) { return new DebuggingSidebarCallStackPane(view); } private Listener delegateListener; @VisibleForTesting DebuggingSidebarCallStackPane(View view) { super(view); view.setDelegate(new ViewEvents() { @Override public void onCallFrameSelect(int depth) { if (delegateListener != null) { delegateListener.onCallFrameSelect(depth); } } }); } void setListener(Listener listener) { delegateListener = listener; } void addCallFrame(String title, String subtitle) { getView().addCallFrame(title, subtitle); } void clearCallStack() { getView().clearCallStack(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/Breakpoint.java
client/src/main/java/com/google/collide/client/code/debugging/Breakpoint.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.PathUtil; import com.google.common.base.Objects; import com.google.common.base.Strings; /** * Represents a breakpoint. This class is immutable. */ public class Breakpoint { private final PathUtil path; private final int lineNumber; private final String condition; private final boolean active; private Breakpoint(Builder builder) { this.path = builder.path; this.lineNumber = builder.lineNumber; this.condition = Strings.nullToEmpty(builder.condition); this.active = builder.active; } public PathUtil getPath() { return path; } public int getLineNumber() { return lineNumber; } public String getCondition() { return condition; } public boolean isActive() { return active; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Breakpoint) { Breakpoint that = (Breakpoint) obj; return Objects.equal(this.lineNumber, that.lineNumber) && Objects.equal(this.active, that.active) && Objects.equal(this.path, that.path) && Objects.equal(this.condition, that.condition); } return false; } @Override public int hashCode() { return Objects.hashCode(path, lineNumber, condition, active); } @Override public String toString() { return "{Breakpoint @" + path + " #" + lineNumber + "}"; } /** * Builder class for the {@link Breakpoint}. */ public static class Builder { private PathUtil path; private int lineNumber; private String condition; private boolean active = true; // Active by default. public Builder(Breakpoint breakpoint) { this.path = breakpoint.path; this.lineNumber = breakpoint.lineNumber; this.condition = breakpoint.condition; this.active = breakpoint.active; } public Builder(PathUtil path, int lineNumber) { this.path = path; this.lineNumber = lineNumber; } public Builder setPath(PathUtil path) { this.path = path; return this; } public Builder setLineNumber(int lineNumber) { this.lineNumber = lineNumber; return this; } public Builder setCondition(String condition) { this.condition = condition; return this; } public Builder setActive(boolean active) { this.active = active; return this; } public Breakpoint build() { return new Breakpoint(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/DebuggingModelController.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingModelController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.common.CanRunApplication; import com.google.collide.client.bootstrap.BootstrapSession; import com.google.collide.client.code.FileSelectedPlace; import com.google.collide.client.code.RightSidebarExpansionEvent; import com.google.collide.client.code.popup.EditorPopupController; import com.google.collide.client.communication.ResourceUriUtils; import com.google.collide.client.document.DocumentManager; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.gutter.Gutter; import com.google.collide.client.history.Place; import com.google.collide.client.util.PathUtil; import com.google.collide.client.workspace.PopupBlockedInstructionalPopup; import com.google.collide.client.workspace.RunApplicationEvent; 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.util.ListenerRegistrar; import com.google.common.base.Preconditions; import elemental.client.Browser; import elemental.dom.Element; import elemental.html.Window; /** * A controller for the debugging model state. */ public class DebuggingModelController <R extends DebuggingModelRenderer.Resources & PopupBlockedInstructionalPopup.Resources & EvaluationPopupController.Resources & DebuggingSidebar.Resources> implements CanRunApplication { public static <R extends DebuggingModelRenderer.Resources & PopupBlockedInstructionalPopup.Resources & EvaluationPopupController.Resources & DebuggingSidebar.Resources> DebuggingModelController<R> create(Place currentPlace, R resources, DebuggingModel debuggingModel, Editor editor, EditorPopupController editorPopupController, DocumentManager documentManager) { DebuggingModelController<R> dmc = new DebuggingModelController<R>(currentPlace, resources, debuggingModel, editor, editorPopupController, documentManager); dmc.populateDebuggingSidebar(); // Register the DebuggingModelController as a handler for clicks on the // Header's run button. currentPlace.registerSimpleEventHandler(RunApplicationEvent.TYPE, dmc.runApplicationHandler); return dmc; } /** * Flag indicating that "popup blocked" alert was shown once to user, so we * should not annoy user with it again. * * <p>This flag is used by and changed by {@link #createOrOpenPopup}. */ private static boolean doNotShowPopupBlockedInstruction; /** * Creates or reuses launchpad window. * * <p>This method should be called from user initiated event handler. * * <p>If popup window already exists, it is cleared. Launchpad is filled * with disclaimer that informs user that deployment is in progress. * * <p>Actually, popup is never blocked, because it is initiated by user. * But in case it is not truth, we show alert to user that instructs how to * enable popups. */ public static Window createOrOpenPopup(PopupBlockedInstructionalPopup.Resources res) { Window popup = Browser.getWindow().open("", BootstrapSession.getBootstrapSession().getActiveClientId()); if (popup == null) { if (!doNotShowPopupBlockedInstruction) { doNotShowPopupBlockedInstruction = true; PopupBlockedInstructionalPopup.create(res).show(); } } return popup; } /** * Handler for clicks on the run button on the workspace header. */ private final RunApplicationEvent.Handler runApplicationHandler = new RunApplicationEvent.Handler() { @Override public void onRunButtonClicked(RunApplicationEvent evt) { runApplication(evt.getUrl()); } }; private final DebuggingModel.DebuggingModelChangeListener debuggingModelChangeListener = new DebuggingModel.DebuggingModelChangeListener() { @Override public void onBreakpointAdded(Breakpoint newBreakpoint) { if (shouldProcessBreakpoint(newBreakpoint) && !breakpoints.contains(newBreakpoint)) { anchorBreakpointAndUpdateSidebar(newBreakpoint); debuggingModelRenderer.renderBreakpointOnGutter( newBreakpoint.getLineNumber(), newBreakpoint.isActive()); } debuggerState.setBreakpoint(newBreakpoint); debuggingSidebar.addBreakpoint(newBreakpoint); } @Override public void onBreakpointRemoved(Breakpoint oldBreakpoint) { if (shouldProcessBreakpoint(oldBreakpoint) && breakpoints.contains(oldBreakpoint)) { breakpoints.removeBreakpoint(oldBreakpoint); debuggingModelRenderer.removeBreakpointOnGutter(oldBreakpoint.getLineNumber()); } debuggerState.removeBreakpoint(oldBreakpoint); debuggingSidebar.removeBreakpoint(oldBreakpoint); } @Override public void onBreakpointReplaced(Breakpoint oldBreakpoint, Breakpoint newBreakpoint) { /* * If a breakpoint is not in the document being displayed, we do not * know the code line that it was attached to, thus we save the old * breakpoint's line, if any. */ String breakpointLine = debuggingSidebar.getBreakpointLineText(oldBreakpoint); onBreakpointRemoved(oldBreakpoint); onBreakpointAdded(newBreakpoint); if (!shouldProcessBreakpoint(newBreakpoint)) { debuggingSidebar.updateBreakpoint(newBreakpoint, breakpointLine); } } @Override public void onPauseOnExceptionsModeUpdated(DebuggingModel.PauseOnExceptionsMode oldMode, DebuggingModel.PauseOnExceptionsMode newMode) { // TODO: Implement this in the UI. // TODO: Update DebuggerState. } @Override public void onBreakpointsEnabledUpdated(boolean newValue) { debuggerState.setBreakpointsEnabled(newValue); debuggingSidebar.setAllBreakpointsActive(newValue); } }; private final Gutter.ClickListener leftGutterClickListener = new Gutter.ClickListener() { @Override public void onClick(int y) { int lineNumber = editor.getBuffer().convertYToLineNumber(y, true); for (int i = 0; i < breakpoints.size(); ++i) { Breakpoint breakpoint = breakpoints.get(i); if (breakpoint.getLineNumber() == lineNumber) { debuggingModel.removeBreakpoint(breakpoint); return; } } if (!isCurrentDocumentEligibleForDebugging()) { return; } Breakpoint breakpoint = new Breakpoint.Builder(path, lineNumber).build(); debuggingModel.addBreakpoint(breakpoint); // Show the sidebar if the very first breakpoint has just been set. maybeShowSidebar(); } }; private boolean isCurrentDocumentEligibleForDebugging() { Preconditions.checkNotNull(path); // TODO: Be more smart here. Also what about source mappings? String baseName = path.getBaseName().toLowerCase(); return baseName.endsWith(".js") || baseName.endsWith(".htm") || baseName.endsWith(".html"); } /** * Handler that receives events from the remote debugger about changes of it's * state (e.g. a {@code running} debugger changed to {@code paused}, etc.). */ private final DebuggerState.DebuggerStateListener debuggerStateListener = new DebuggerState.DebuggerStateListener() { @Override public void onDebuggerStateChange() { if (debuggerState.isPaused()) { showSidebar(); } debuggingModelRenderer.renderDebuggerState(); handleOnCallFrameSelect(0); } }; /** * Handler that receives user commands, such as clicks on the debugger control * buttons in the sidebar. */ private final DebuggingSidebar.DebuggerCommandListener userCommandListener = new DebuggingSidebar.DebuggerCommandListener() { @Override public void onPause() { debuggerState.pause(); } @Override public void onResume() { debuggerState.resume(); } @Override public void onStepOver() { debuggerState.stepOver(); } @Override public void onStepInto() { debuggerState.stepInto(); } @Override public void onStepOut() { debuggerState.stepOut(); } @Override public void onCallFrameSelect(int depth) { handleOnCallFrameSelect(depth); } @Override public void onBreakpointIconClick(Breakpoint breakpoint) { Breakpoint newBreakpoint = new Breakpoint.Builder(breakpoint) .setActive(!breakpoint.isActive()) .build(); debuggingModel.updateBreakpoint(breakpoint, newBreakpoint); } @Override public void onBreakpointLineClick(Breakpoint breakpoint) { maybeNavigateToDocument(breakpoint.getPath(), breakpoint.getLineNumber()); } @Override public void onActivateBreakpoints() { debuggingModel.setBreakpointsEnabled(true); } @Override public void onDeactivateBreakpoints() { debuggingModel.setBreakpointsEnabled(false); } @Override public void onLocationLinkClick(String url, int lineNumber) { SourceMapping sourceMapping = debuggerState.getSourceMapping(); if (sourceMapping == null) { // Ignore. Maybe the debugger has just been shutdown. return; } PathUtil path = sourceMapping.getLocalSourcePath(url); if (path != null) { maybeNavigateToDocument(path, lineNumber); } } }; /** * Handler that receives notifications when a breakpoint description changes. */ private final AnchoredBreakpoints.BreakpointDescriptionListener breakpointDescriptionListener = new AnchoredBreakpoints.BreakpointDescriptionListener() { @Override public void onBreakpointDescriptionChange(Breakpoint breakpoint, String newText) { debuggingSidebar.updateBreakpoint(breakpoint, newText); } }; private final PopupBlockedInstructionalPopup.Resources popupResources; private final Editor editor; private final DebuggingModel debuggingModel; private final ListenerRegistrar.Remover leftGutterClickListenerRemover; private final DebuggerState debuggerState; private final DebuggingSidebar debuggingSidebar; private final DebuggingModelRenderer debuggingModelRenderer; private final Place currentPlace; private final CssLiveEditController cssLiveEditController; private final EvaluationPopupController evaluationPopupController; private PathUtil path; private AnchoredBreakpoints breakpoints; /** * Indicator that sidebar has been discovered by user. */ private boolean sidebarDiscovered; private DebuggingModelController(Place currentPlace, R resources, DebuggingModel debuggingModel, Editor editor, EditorPopupController editorPopupController, DocumentManager documentManager) { this.popupResources = resources; this.editor = editor; this.currentPlace = currentPlace; this.debuggingModel = debuggingModel; this.leftGutterClickListenerRemover = editor.getLeftGutter().getClickListenerRegistrar().add(leftGutterClickListener); // Every time we enter workspace, we get a new debugging session id. String sessionId = BootstrapSession.getBootstrapSession().getActiveClientId() + ":" + System.currentTimeMillis(); this.debuggerState = DebuggerState.create(sessionId); this.debuggingSidebar = DebuggingSidebar.create(resources, debuggerState); this.debuggingModelRenderer = DebuggingModelRenderer.create(resources, editor, debuggingSidebar, debuggerState); this.cssLiveEditController = new CssLiveEditController(debuggerState, documentManager); this.evaluationPopupController = EvaluationPopupController.create( resources, editor, editorPopupController, debuggerState); this.debuggingModel.addModelChangeListener(debuggingModelChangeListener); this.debuggerState.getDebuggerStateListenerRegistrar().add(debuggerStateListener); this.debuggingSidebar.getDebuggerCommandListenerRegistrar().add(userCommandListener); } public void setDocument(Document document, PathUtil path, DocumentParser parser) { if (breakpoints != null) { breakpoints.teardown(); debuggingModelRenderer.handleDocumentChanged(); } this.path = path; breakpoints = new AnchoredBreakpoints(debuggingModel, document); anchorBreakpoints(); maybeAnchorExecutionLine(); evaluationPopupController.setDocument(document, path, parser); breakpoints.setBreakpointDescriptionListener(breakpointDescriptionListener); } public Element getDebuggingSidebarElement() { return debuggingSidebar.getView().getElement(); } /** * @see #runApplication(String) */ public boolean runApplication(PathUtil applicationPath) { String baseUri = ResourceUriUtils.getAbsoluteResourceBaseUri(); SourceMapping sourceMapping = StaticSourceMapping.create(baseUri); return runApplication(sourceMapping, sourceMapping.getRemoteSourceUri(applicationPath)); } /** * Runs a given resource via debugger API if it is available, or just opens * the resource in a new window. * * @param absoluteResourceUri absolute resource URI * @return {@code true} if the application was started successfully via * debugger API, {@code false} if it was opened in a new window */ public boolean runApplication(String absoluteResourceUri) { final String baseUri; // Check if the URI points to a local path. String workspaceBaseUri = ResourceUriUtils.getAbsoluteResourceBaseUri(); if (absoluteResourceUri.startsWith(workspaceBaseUri + "/")) { baseUri = workspaceBaseUri; } else { baseUri = ResourceUriUtils.extractBaseUri(absoluteResourceUri); } SourceMapping sourceMapping = StaticSourceMapping.create(baseUri); return runApplication(sourceMapping, absoluteResourceUri); } private boolean runApplication(SourceMapping sourceMapping, String absoluteResourceUri) { if (debuggerState.isDebuggerAvailable()) { debuggerState.runDebugger(sourceMapping, absoluteResourceUri); JsonArray<Breakpoint> allBreakpoints = debuggingModel.getBreakpoints(); for (int i = 0; i < allBreakpoints.size(); ++i) { debuggerState.setBreakpoint(allBreakpoints.get(i)); } debuggerState.setBreakpointsEnabled(debuggingModel.isBreakpointsEnabled()); return true; } else { Window popup = createOrOpenPopup(popupResources); if (popup != null) { popup.getLocation().assign(absoluteResourceUri); // Show the sidebar once to promote the Debugger Extension. maybeShowSidebar(); } return false; } } private void anchorBreakpoints() { JsonArray<Breakpoint> allBreakpoints = debuggingModel.getBreakpoints(); for (int i = 0; i < allBreakpoints.size(); ++i) { Breakpoint breakpoint = allBreakpoints.get(i); if (path.equals(breakpoint.getPath())) { anchorBreakpointAndUpdateSidebar(breakpoint); debuggingModelRenderer.renderBreakpointOnGutter( breakpoint.getLineNumber(), breakpoint.isActive()); } } } private void populateDebuggingSidebar() { JsonArray<Breakpoint> allBreakpoints = debuggingModel.getBreakpoints(); for (int i = 0; i < allBreakpoints.size(); ++i) { debuggingSidebar.addBreakpoint(allBreakpoints.get(i)); } } private void anchorBreakpointAndUpdateSidebar(Breakpoint breakpoint) { Anchor anchor = breakpoints.anchorBreakpoint(breakpoint); debuggingSidebar.updateBreakpoint(breakpoint, anchor.getLine().getText()); } private void maybeAnchorExecutionLine() { PathUtil callFramePath = debuggerState.getActiveCallFramePath(); if (callFramePath != null && callFramePath.equals(path)) { int lineNumber = debuggerState.getActiveCallFrameExecutionLineNumber(); if (lineNumber >= 0) { debuggingModelRenderer.renderExecutionLine(lineNumber); } } } private void showSidebar() { sidebarDiscovered = true; currentPlace.fireEvent(new RightSidebarExpansionEvent(true)); } /** * Shows sidebar in case user hasn't discovered yet, and at least one * breakpoint is set. */ private void maybeShowSidebar() { if (!sidebarDiscovered && debuggingModel.getBreakpointCount() != 0) { showSidebar(); } } private boolean shouldProcessBreakpoint(Breakpoint breakpoint) { return path != null && path.equals(breakpoint.getPath()); } private void handleOnCallFrameSelect(int callFrameDepth) { debuggerState.setActiveCallFrameIndex(callFrameDepth); debuggingModelRenderer.renderDebuggerCallFrame(); PathUtil callFramePath = debuggerState.getActiveCallFramePath(); if (callFramePath == null) { // Not paused, remove the execution line (if any). debuggingModelRenderer.removeExecutionLine(); return; } maybeAnchorExecutionLine(); int lineNumber = debuggerState.getActiveCallFrameExecutionLineNumber(); maybeNavigateToDocument(callFramePath, lineNumber); } private void maybeNavigateToDocument(PathUtil documentPath, int lineNumber) { if (documentPath.equals(this.path)) { editor.getFocusManager().focus(); editor.scrollTo(lineNumber, 0); } else { currentPlace.fireChildPlaceNavigation( FileSelectedPlace.PLACE.createNavigationEvent(documentPath, lineNumber)); } } public void cleanup() { debuggerState.shutdown(); leftGutterClickListenerRemover.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/debugging/EvaluationPopupController.java
client/src/main/java/com/google/collide/client/code/debugging/EvaluationPopupController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnEvaluateExpressionResponse; import com.google.collide.client.code.popup.EditorPopupController; import com.google.collide.client.documentparser.DocumentParser; import com.google.collide.client.editor.Editor; import com.google.collide.client.editor.MouseHoverManager; import com.google.collide.client.ui.menu.PositionController.VerticalAlign; import com.google.collide.client.util.PathUtil; 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.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar.RemoverManager; import com.google.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; /** * Controller for the debugger evaluation expression popup. */ public class EvaluationPopupController { public interface Css extends CssResource { String popupAnchor(); } public interface Resources extends ClientBundle, RemoteObjectTree.Resources { @Source("EvaluationPopupController.css") Css evaluationPopupControllerCss(); } static EvaluationPopupController create(Resources resources, Editor editor, EditorPopupController popupController, DebuggerState debuggerState) { return new EvaluationPopupController(resources, editor, popupController, debuggerState); } private class DebuggerListenerImpl implements DebuggerState.DebuggerStateListener, DebuggerState.EvaluateExpressionListener { private boolean isAttached; private final RemoverManager removerManager = new RemoverManager(); @Override public void onDebuggerStateChange() { handleOnDebuggerStateChange(); } @Override public void onEvaluateExpressionResponse(OnEvaluateExpressionResponse response) { handleOnEvaluateExpressionResponse(response); } @Override public void onGlobalObjectChanged() { hidePopup(); } boolean attach() { if (!isAttached) { isAttached = true; removerManager.track(debuggerState.getDebuggerStateListenerRegistrar().add(this)); removerManager.track(debuggerState.getEvaluateExpressionListenerRegistrar().add(this)); return true; } return false; } void detach() { if (isAttached) { isAttached = false; removerManager.remove(); } } } private final Css css; private final Editor editor; private final EditorPopupController popupController; private final DebuggerState debuggerState; private final DebuggerListenerImpl debuggerListener = new DebuggerListenerImpl(); private final EvaluableExpressionFinder expressionFinder = new EvaluableExpressionFinder(); private final RemoteObjectTree remoteObjectTree; private final RemoverManager removerManager = new RemoverManager(); private final Element popupRootElement; private DocumentParser documentParser; private EditorPopupController.Remover editorPopupControllerRemover; private LineInfo lastExpressionLineInfo; private EvaluableExpressionFinder.Result lastExpressionResult; private boolean awaitingExpressionEvaluation; private final EditorPopupController.PopupRenderer popupRenderer = new EditorPopupController.PopupRenderer() { @Override public Element renderDom() { RemoteObjectNode root = remoteObjectTree.getRoot(); RemoteObjectNode rootChild = (root == null ? null : root.getChildren().get(0)); // The left margin is different for expandable and non-expandable boolean expandable = (rootChild != null && rootChild.hasChildren()); if (expandable) { popupRootElement.getStyle().setMarginLeft(-7, CSSStyleDeclaration.Unit.PX); } else { popupRootElement.getStyle().setMarginLeft(-17, CSSStyleDeclaration.Unit.PX); } return popupRootElement; } }; private final MouseHoverManager.MouseHoverListener mouseHoverListener = new MouseHoverManager.MouseHoverListener() { @Override public void onMouseHover(int x, int y, LineInfo lineInfo, int column) { handleOnMouseHover(lineInfo, column); } }; private EvaluationPopupController(Resources resources, Editor editor, EditorPopupController popupController, DebuggerState debuggerState) { this.css = resources.evaluationPopupControllerCss(); this.editor = editor; this.popupController = popupController; this.debuggerState = debuggerState; this.remoteObjectTree = RemoteObjectTree.create( new RemoteObjectTree.View(resources), resources, debuggerState); this.popupRootElement = createPopupRootElement(); } private Element createPopupRootElement() { Element root = Elements.createDivElement(); CssUtils.setUserSelect(root, false); root.appendChild(remoteObjectTree.getView().getElement()); return root; } void setDocument(Document document, PathUtil path, @Nullable DocumentParser documentParser) { hidePopup(); if (path.getBaseName().endsWith(".js")) { this.documentParser = documentParser; if (debuggerListener.attach()) { // Initialize with the current debugger state. handleOnDebuggerStateChange(); } } else { this.documentParser = null; debuggerListener.detach(); removerManager.remove(); } } private void hidePopup() { if (editorPopupControllerRemover != null) { editorPopupControllerRemover.remove(); editorPopupControllerRemover = null; } lastExpressionLineInfo = null; lastExpressionResult = null; remoteObjectTree.setRoot(null); awaitingExpressionEvaluation = false; } private boolean isLastPopupVisible() { return editorPopupControllerRemover != null && editorPopupControllerRemover.isVisibleOrPending(); } private boolean registerNewFinderResult(LineInfo lineInfo, EvaluableExpressionFinder.Result result) { if (isLastPopupVisible() && lineInfo.equals(lastExpressionLineInfo) && lastExpressionResult != null && lastExpressionResult.getStartColumn() == result.getStartColumn() && lastExpressionResult.getEndColumn() == result.getEndColumn() && lastExpressionResult.getExpression().equals(result.getExpression())) { // The same result was found - no need to hide and reopen the same popup. popupController.cancelPendingHide(); return false; } hidePopup(); lastExpressionLineInfo = lineInfo; lastExpressionResult = result; awaitingExpressionEvaluation = true; return true; } private void handleOnDebuggerStateChange() { if (debuggerState.isPaused()) { removerManager.track(editor.getMouseHoverManager().addMouseHoverListener(mouseHoverListener)); } else { removerManager.remove(); hidePopup(); } } private void handleOnMouseHover(LineInfo lineInfo, int column) { EvaluableExpressionFinder.Result result = expressionFinder.find(lineInfo, column, documentParser); if (result != null) { if (registerNewFinderResult(lineInfo, result)) { debuggerState.evaluateExpression(result.getExpression()); } } else { hidePopup(); } } private void handleOnEvaluateExpressionResponse(OnEvaluateExpressionResponse response) { if (!awaitingExpressionEvaluation || isLastPopupVisible() || response.wasThrown() || lastExpressionLineInfo == null || lastExpressionResult == null || !lastExpressionResult.getExpression().equals(response.getExpression())) { return; } awaitingExpressionEvaluation = false; RemoteObjectNode newRoot = RemoteObjectNode.createRoot(); RemoteObjectNode child = new RemoteObjectNode.Builder(response.getExpression(), response.getResult()) .setDeletable(false) .build(); newRoot.addChild(child); remoteObjectTree.setRoot(newRoot); JsonArray<Element> popupPartnerElements = JsonCollections.createArray(remoteObjectTree.getContextMenuElement()); editorPopupControllerRemover = popupController.showPopup(lastExpressionLineInfo, lastExpressionResult.getStartColumn(), lastExpressionResult.getEndColumn(), css.popupAnchor(), popupRenderer, popupPartnerElements, VerticalAlign.BOTTOM, true /* shouldCaptureOutsideClickOnClose */, 0 /* delayMs */); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/EvaluableExpressionFinder.java
client/src/main/java/com/google/collide/client/code/debugging/EvaluableExpressionFinder.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.documentparser.DocumentParser; import com.google.collide.client.documentparser.ParseResult; import com.google.collide.codemirror2.JsState; 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.document.Position; import com.google.collide.shared.util.StringUtils; import com.google.common.annotations.VisibleForTesting; /** * Encapsulates an algorithm to find a shortest evaluable JavaScript expression * by a given position in the text. * */ class EvaluableExpressionFinder { /** * Represents the result of the evaluable expression search. */ interface Result { /** * @return column of the first expression's character (inclusive) */ int getStartColumn(); /** * @return column of the last expression's character (inclusive) */ int getEndColumn(); /** * @return the expression found */ String getExpression(); } /** * @see #find(LineInfo, int, DocumentParser) */ @VisibleForTesting Result find(String text, int column) { if (column < 0 || column >= text.length()) { return null; } int left = -1; int right = -1; char ch = text.charAt(column); // A special case of pointing to a quote character that is next to a square bracket. if (StringUtils.isQuote(ch)) { if (column > 0 && text.charAt(column - 1) == '[') { ch = '['; --column; } else if (column + 1 < text.length() && text.charAt(column + 1) == ']') { ch = ']'; ++column; } else { return null; } } if (ch == '.' || isValidCharacterForJavaScriptName(ch)) { left = expandLeftBorder(text, column); right = expandRightBorder(text, column); } else if (ch == '[') { right = expandRightBracket(text, column); if (right != -1) { left = expandLeftBorder(text, column); } } else if (ch == ']') { right = column; left = expandLeftBracket(text, column); if (left != -1) { left = expandLeftBorder(text, left); } } // A special case of pointing to a numeric array index inside square brackets. if (left != -1 && right != -1 && isOnlyDigits(text, left, right)) { if (left > 0 && text.charAt(left - 1) == '[' && right + 1 < text.length() && text.charAt(right + 1) == ']') { left = expandLeftBorder(text, left - 1); ++right; } else { return null; } } if (left != -1 && right != -1) { final int startColumn = left; final int endColumn = right; final String expression = text.substring(left, right + 1); return new Result() { @Override public int getStartColumn() { return startColumn; } @Override public int getEndColumn() { return endColumn; } @Override public String getExpression() { return expression; } }; } return null; } private static int expandLeftBorder(String text, int column) { while (column > 0) { char ch = text.charAt(column - 1); if (ch == '.' || isValidCharacterForJavaScriptName(ch)) { --column; } else if (ch == ']') { column = expandLeftBracket(text, column - 1); } else { break; } } return column; } private static int expandLeftBracket(String text, int column) { int bracketLevel = 1; for (--column; column >= 0; --column) { char ch = text.charAt(column); if (StringUtils.isQuote(ch)) { column = expandLeftQuote(text, column); if (column == -1) { return -1; } } else if (ch == ']') { ++bracketLevel; } else if (ch == '[') { --bracketLevel; if (bracketLevel == 0) { return column; } } else if (ch != '.' && !isValidCharacterForJavaScriptName(ch)) { return -1; } } return -1; } private static int expandLeftQuote(String text, int column) { char quote = text.charAt(column); if (!StringUtils.isQuote(quote)) { return -1; } for (--column; column >= 0; --column) { char ch = text.charAt(column); if (ch == quote) { // Check for escape chars. boolean escapeChar = false; for (int i = column - 1;; --i) { if (i >= 0 && text.charAt(i) == '\\') { escapeChar = !escapeChar; } else { if (!escapeChar) { return column; } column = i + 1; break; } } } } return -1; } private static int expandRightBorder(String text, int column) { while (column + 1 < text.length()) { char ch = text.charAt(column + 1); if (isValidCharacterForJavaScriptName(ch)) { ++column; } else { break; } } return column; } private static int expandRightBracket(String text, int column) { int bracketLevel = 1; for (++column; column < text.length(); ++column) { char ch = text.charAt(column); if (StringUtils.isQuote(ch)) { column = expandRightQuote(text, column); if (column == -1) { return -1; } } else if (ch == '[') { ++bracketLevel; } else if (ch == ']') { --bracketLevel; if (bracketLevel == 0) { return column; } } else if (ch != '.' && !isValidCharacterForJavaScriptName(ch)) { return -1; } } return -1; } private static int expandRightQuote(String text, int column) { char quote = text.charAt(column); if (!StringUtils.isQuote(quote)) { return -1; } boolean escapeChar = false; for (++column; column < text.length(); ++column) { char ch = text.charAt(column); if (ch == '\\') { escapeChar = !escapeChar; } else { if (ch == quote && !escapeChar) { return column; } escapeChar = false; } } return -1; } private static boolean isOnlyDigits(String text, int left, int right) { for (int i = left; i <= right; ++i) { if (!StringUtils.isNumeric(text.charAt(i))) { return false; } } return true; } private static boolean isValidCharacterForJavaScriptName(char ch) { return StringUtils.isAlphaNumOrUnderscore(ch) || ch == '$'; } /** * Finds a shortest evaluable JavaScript expression around a given position * in the document. * * @param lineInfo the line to examine * @param column the seed position to start with * @param parser document parser * @return a new instance of {@link Result}, or {@code null} if no expression * was found */ @SuppressWarnings("incomplete-switch") Result find(LineInfo lineInfo, int column, @Nullable DocumentParser parser) { Result result = find(lineInfo.line().getText(), column); if (result == null || parser == null) { return result; } // Use the parser information to determine if we are inside a comment // or a string or any other place that does not make sense to evaluate. Position endPosition = new Position(lineInfo, result.getEndColumn() + 1); ParseResult<JsState> parseResult = parser.getState(JsState.class, endPosition, null); if (parseResult == null) { return result; } JsonArray<Token> tokens = parseResult.getTokens(); Token lastToken = tokens.isEmpty() ? null : tokens.get(tokens.size() - 1); if (lastToken != null) { switch (lastToken.getType()) { case ATOM: case COMMENT: case KEYWORD: case NUMBER: case STRING: case REGEXP: return null; } } 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/code/debugging/CssLiveEditController.java
client/src/main/java/com/google/collide/client/code/debugging/CssLiveEditController.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Nonnull; import javax.annotation.Nullable; import com.google.collide.client.code.debugging.DebuggerApiTypes.CssStyleSheetHeader; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnAllCssStyleSheetsResponse; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnEvaluateExpressionResponse; import com.google.collide.client.document.DocumentManager; import com.google.collide.client.util.DeferredCommandExecutor; import com.google.collide.client.util.PathUtil; import com.google.collide.dto.FileContents; import com.google.collide.json.shared.JsonArray; import com.google.collide.shared.document.Document; import com.google.collide.shared.document.TextChange; import com.google.collide.shared.util.JsonCollections; import com.google.collide.shared.util.ListenerRegistrar.RemoverManager; import com.google.common.base.Preconditions; /** * Controller for live edits of CSS files during debugging. * * <p>Schedules propagation of CSS edits to the debugger. * */ class CssLiveEditController { /** * Bean containing information about document binding and update status. */ private static class DocumentInfo { @Nullable private Document document; @Nonnull private final String styleSheetId; @Nonnull private final PathUtil path; /** * Indicator that file has changed, but changes hasn't been sent to debugger. */ private boolean dirty; private DocumentInfo(@Nonnull String styleSheetId, @Nonnull PathUtil path) { Preconditions.checkNotNull(styleSheetId); Preconditions.checkNotNull(path); this.path = path; this.styleSheetId = styleSheetId; } } private final DocumentManager documentManager; private final DebuggerState debuggerState; private final EventsListenerImpl eventsListener; /** * Executor that sends content of marked documents to debugger * and then clears marks. */ private final DeferredCommandExecutor updatesApplier = new DeferredCommandExecutor(100) { @Override protected boolean execute() { if (debuggerState.isActive()) { for (DocumentInfo documentInfo : trackedDocuments.asIterable()) { if (documentInfo.dirty) { documentInfo.dirty = false; Document document = Preconditions.checkNotNull(documentInfo.document); String styleSheetId = Preconditions.checkNotNull(documentInfo.styleSheetId); debuggerState.setStyleSheetText(styleSheetId, document.asText()); } } } return false; } }; // TODO: Can Chrome notify us when list changes? /** * Executor that periodically requests list of used CSS from debugger. */ private final DeferredCommandExecutor trackListUpdater = new DeferredCommandExecutor(100) { @Override protected boolean execute() { if (debuggerState.isActive()) { debuggerState.requestAllCssStyleSheets(); } return true; } }; /** * List of documents that are currently tracked. */ private final JsonArray<DocumentInfo> trackedDocuments = JsonCollections.createArray(); private final RemoverManager removerManager = new RemoverManager(); private class EventsListenerImpl implements DebuggerState.DebuggerStateListener, DebuggerState.CssListener, DebuggerState.EvaluateExpressionListener { @Override public void onAllCssStyleSheetsResponse(OnAllCssStyleSheetsResponse response) { handleOnAllCssStyleSheetsResponse(response); } @Override public void onDebuggerStateChange() { updateLiveEditListenerState(); } @Override public void onEvaluateExpressionResponse(OnEvaluateExpressionResponse response) { } @Override public void onGlobalObjectChanged() { // Invalidate the cached stylesheet ID. updateLiveEditListenerState(); } } /** * Marks specified document for update and schedules update is necessary. */ private void scheduleUpdate(@Nonnull DocumentInfo documentInfo) { Preconditions.checkNotNull(documentInfo); if (!debuggerState.isActive()) { return; } Preconditions.checkNotNull(documentInfo.document); if (documentInfo.dirty) { return; } documentInfo.dirty = true; if (!updatesApplier.isScheduled()) { updatesApplier.schedule(1); } } CssLiveEditController(DebuggerState debuggerState, DocumentManager documentManager) { this.debuggerState = debuggerState; this.documentManager = documentManager; this.eventsListener = new EventsListenerImpl(); debuggerState.getDebuggerStateListenerRegistrar().add(eventsListener); debuggerState.getCssListenerRegistrar().add(eventsListener); debuggerState.getEvaluateExpressionListenerRegistrar().add(eventsListener); } private void updateLiveEditListenerState() { untrackAll(); trackListUpdater.cancel(); if (debuggerState.isActive()) { trackListUpdater.schedule(1); } } /** * Registers all CSS paths / styleSheetIds that are in use. */ private void handleOnAllCssStyleSheetsResponse(OnAllCssStyleSheetsResponse response) { if (!debuggerState.isActive()) { return; } JsonArray<DocumentInfo> freshList = buildDocumentInfoList(response); if (checkForEquality(freshList, trackedDocuments)) { return; } untrackAll(); for (final DocumentInfo documentInfo : freshList.asIterable()) { trackedDocuments.add(documentInfo); documentManager.getDocument(documentInfo.path, new DocumentManager.GetDocumentCallback() { @Override public void onDocumentReceived(Document document) { // This method can be called asynchronously. If item is not in list // then ignore this notification. "equals" is not overridden, so // "contains" reports that list contains given reference. if (!trackedDocuments.contains(documentInfo)) { return; } documentInfo.document = document; removerManager.track(document.getTextListenerRegistrar().add(new Document.TextListener() { @Override public void onTextChange(Document document, JsonArray<TextChange> textChanges) { scheduleUpdate(documentInfo); } })); // Schedule update, because debugger can have stale version in use. scheduleUpdate(documentInfo); } @Override public void onUneditableFileContentsReceived(FileContents contents) { // TODO: Well, is it unmodifiable at all, or only for us? } @Override public void onFileNotFoundReceived() { // Do nothing. } }); } } /** * Checks equality of two track-lists. * * <p>Track lists are supposed to be equal if they contain the same set * of (path, styleSheetId) pairs. * * <p>Note: currently we suggest, that list is ordered somehow, so pairs have * matching positions. */ private boolean checkForEquality(JsonArray<DocumentInfo> list1, JsonArray<DocumentInfo> list2) { if (list1.size() != list2.size()) { return false; } for (int i = 0, n = list1.size(); i < n; i++) { DocumentInfo item1 = list1.get(i); DocumentInfo item2 = list2.get(i); if (!item1.styleSheetId.equals(item2.styleSheetId)) { return false; } if (!item1.path.equals(item2.path)) { return false; } } return true; } /** * Builds track-list from debugger response. * * <p>Only ".css" files are accepted. * * <p>Note: For some items URL looks like "data:...". * In that case {@link PathUtil} is {@code null}. */ private JsonArray<DocumentInfo> buildDocumentInfoList(OnAllCssStyleSheetsResponse response) { JsonArray<DocumentInfo> result = JsonCollections.createArray(); JsonArray<CssStyleSheetHeader> headers = response.getHeaders(); for (CssStyleSheetHeader header : headers.asIterable()) { String url = header.getUrl(); PathUtil path = debuggerState.getSourceMapping().getLocalSourcePath(url); if (path == null) { continue; } if (!path.getBaseName().endsWith(".css")) { continue; } String styleSheetId = header.getId(); DocumentInfo docInfo = new DocumentInfo(styleSheetId, path); result.add(docInfo); } return result; } /** * Unregisters text-change listeners, stops appropriate executors and * cleans track list. */ private void untrackAll() { removerManager.remove(); trackedDocuments.clear(); updatesApplier.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/code/debugging/RemoteObjectNodeDataAdapter.java
client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectNodeDataAdapter.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.NodeDataAdapter; import collide.client.treeview.TreeNodeElement; import com.google.collide.json.shared.JsonArray; /** * A {@link NodeDataAdapter} for the {@link RemoteObjectNode}. */ class RemoteObjectNodeDataAdapter implements NodeDataAdapter<RemoteObjectNode> { @Override public int compare(RemoteObjectNode a, RemoteObjectNode b) { return a.compareTo(b); } @Override public boolean hasChildren(RemoteObjectNode data) { return data.hasChildren(); } @Override public JsonArray<RemoteObjectNode> getChildren(RemoteObjectNode data) { return data.getChildren(); } @Override public String getNodeId(RemoteObjectNode data) { return data.getNodeId(); } @Override public String getNodeName(RemoteObjectNode data) { return data.getName(); } @Override public RemoteObjectNode getParent(RemoteObjectNode data) { return data.getParent(); } @Override public TreeNodeElement<RemoteObjectNode> getRenderedTreeNode(RemoteObjectNode data) { return data.getRenderedTreeNode(); } @Override public void setNodeName(RemoteObjectNode data, String name) { data.setName(name); } @Override public void setRenderedTreeNode(RemoteObjectNode data, TreeNodeElement<RemoteObjectNode> renderedNode) { data.setRenderedTreeNode(renderedNode); } @Override public RemoteObjectNode getDragDropTarget(RemoteObjectNode data) { return data; } @Override public JsonArray<String> getNodePath(RemoteObjectNode data) { return NodeDataAdapter.PathUtils.getNodePath(this, data); } @Override public RemoteObjectNode getNodeByPath(RemoteObjectNode root, JsonArray<String> relativeNodePath) { // TODO: Not yet implemented. Also not used by the debug 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/code/debugging/RemoteObjectNodeCache.java
client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectNodeCache.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.RemoteObjectId; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; import com.google.collide.shared.util.JsonCollections; /** * A cache of {@link RemoteObjectNode} objects. * */ class RemoteObjectNodeCache { private final JsonStringMap<JsonArray<RemoteObjectNode>> cache = JsonCollections.createMap(); /** * Convenience shorthand over the generic {@link JsonStringMap.IterationCallback}. */ public interface IterationCallback extends JsonStringMap.IterationCallback< JsonArray<RemoteObjectNode>> { } public boolean contains(RemoteObjectNode node) { String cacheKey = getCacheKey(node); if (cacheKey == null) { return false; } JsonArray<RemoteObjectNode> array = cache.get(cacheKey); return array != null && array.contains(node); } public JsonArray<RemoteObjectNode> get(RemoteObjectId objectId) { String cacheKey = getCacheKey(objectId); return cacheKey == null ? null : cache.get(cacheKey); } public void put(RemoteObjectNode node) { String cacheKey = getCacheKey(node); if (cacheKey == null) { return; } JsonArray<RemoteObjectNode> array = cache.get(cacheKey); if (array == null) { array = JsonCollections.createArray(); cache.put(cacheKey, array); } array.add(node); } public void remove(RemoteObjectNode node) { String cacheKey = getCacheKey(node); if (cacheKey == null) { return; } JsonArray<RemoteObjectNode> array = cache.get(cacheKey); if (array != null) { array.remove(node); if (array.isEmpty()) { cache.remove(cacheKey); } } } public void iterate(IterationCallback callback) { cache.iterate(callback); } private static String getCacheKey(RemoteObjectNode node) { if (node == null || node.getRemoteObject() == null) { return null; } return getCacheKey(node.getRemoteObject().getObjectId()); } private static String getCacheKey(RemoteObjectId objectId) { return objectId == null ? null : objectId.toString(); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false
WeTheInternet/collide
https://github.com/WeTheInternet/collide/blob/2136cfc9705a96d88c69356868dda5b95c35bc6d/client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebar.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebar.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 collide.client.util.CssUtils; import collide.client.util.Elements; import com.google.collide.client.util.dom.DomUtils; 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.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.gwt.resources.client.ClientBundle; import com.google.gwt.resources.client.CssResource; import com.google.gwt.resources.client.DataResource; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; /** * The presenter for the debugging sidebar. This sidebar shows current debugger * state, call stack, watch expressions, breakpoints and etc. * * TODO: i18n for the UI strings? * */ public class DebuggingSidebar extends UiComponent<DebuggingSidebar.View> { public interface Css extends CssResource { String root(); String unscrollable(); String scrollable(); String expandablePane(); String paneTitle(); String paneTitleText(); String paneBody(); String paneInfo(); String paneInfoHeader(); String paneInfoBody(); String paneData(); String paneExpanded(); } public interface Resources extends ClientBundle, DebuggingSidebarHeader.Resources, DebuggingSidebarControlsPane.Resources, DebuggingSidebarWatchExpressionsPane.Resources, DebuggingSidebarCallStackPane.Resources, DebuggingSidebarScopeVariablesPane.Resources, DebuggingSidebarBreakpointsPane.Resources, DomInspector.Resources, ConsoleView.Resources, DebuggingSidebarNoApiPane.Resources { @Source("DebuggingSidebar.css") Css workspaceEditorDebuggingSidebarCss(); @Source("triangleRight.png") DataResource triangleRightResource(); @Source("triangleDown.png") DataResource triangleDownResource(); } /** * User actions on the debugger. */ public interface DebuggerCommandListener { void onPause(); void onResume(); void onStepOver(); void onStepInto(); void onStepOut(); void onCallFrameSelect(int depth); void onBreakpointIconClick(Breakpoint breakpoint); void onBreakpointLineClick(Breakpoint breakpoint); void onActivateBreakpoints(); void onDeactivateBreakpoints(); void onLocationLinkClick(String url, int lineNumber); } /** * The view for the sidebar. */ public static class View extends CompositeView<Void> { private final Css css; private final DebuggingSidebarHeader.View headerView; private final DebuggingSidebarControlsPane.View controlsPaneView; private final DebuggingSidebarWatchExpressionsPane.View watchExpressionsPaneView; private final DebuggingSidebarCallStackPane.View callStackPaneView; private final DebuggingSidebarScopeVariablesPane.View scopeVariablesPaneView; private final DebuggingSidebarBreakpointsPane.View breakpointsPaneView; private final DomInspector.View domInspectorView; private final ConsoleView.View consoleView; private final DebuggingSidebarNoApiPane.View noApiPaneView; private final Element headerPane; private final Element controlsPane; private final Element watchExpressionsPane; private final Element callStackPane; private final Element scopeVariablesPane; private final Element breakpointsPane; private final Element domInspectorPane; private final Element consolePane; private final Element noApiPane; private final EventListener expandCollapsePaneListener = new EventListener() { @Override public void handleEvent(Event evt) { Element pane = CssUtils.getAncestorOrSelfWithClassName((Element) evt.getTarget(), css.expandablePane()); if (pane != null) { expandPane(pane, !pane.hasClassName(css.paneExpanded())); } } }; public View(Resources resources) { css = resources.workspaceEditorDebuggingSidebarCss(); headerView = new DebuggingSidebarHeader.View(resources); controlsPaneView = new DebuggingSidebarControlsPane.View(resources); watchExpressionsPaneView = new DebuggingSidebarWatchExpressionsPane.View(resources); callStackPaneView = new DebuggingSidebarCallStackPane.View(resources); scopeVariablesPaneView = new DebuggingSidebarScopeVariablesPane.View(resources); breakpointsPaneView = new DebuggingSidebarBreakpointsPane.View(resources); domInspectorView = new DomInspector.View(resources); consoleView = new ConsoleView.View(resources); noApiPaneView = new DebuggingSidebarNoApiPane.View(resources); headerPane = headerView.getElement(); controlsPane = controlsPaneView.getElement(); watchExpressionsPane = createWatchExpressionsPane(); callStackPane = createCallStackPane(); scopeVariablesPane = createScopeVariablesPane(); breakpointsPane = createBreakpointsPane(); domInspectorPane = createDomInspectorPane(); consolePane = createConsolePane(); noApiPane = noApiPaneView.getElement(); Element rootElement = Elements.createDivElement(css.root()); Element unscrollable = Elements.createDivElement(css.unscrollable()); unscrollable.appendChild(headerPane); unscrollable.appendChild(controlsPane); unscrollable.appendChild(noApiPane); Element scrollable = Elements.createDivElement(css.scrollable()); scrollable.appendChild(watchExpressionsPane); scrollable.appendChild(callStackPane); scrollable.appendChild(scopeVariablesPane); scrollable.appendChild(breakpointsPane); scrollable.appendChild(consolePane); scrollable.appendChild(domInspectorPane); rootElement.appendChild(unscrollable); rootElement.appendChild(scrollable); setElement(rootElement); CssUtils.setDisplayVisibility(noApiPane, false); } private Element createWatchExpressionsPane() { return createExpandablePane("Watch Expressions", "No watch expressions", "", watchExpressionsPaneView.getElement()); } private Element createCallStackPane() { return createExpandablePane("Call Stack", "Not paused", "The call stack is a representation of how your code was executed.", callStackPaneView.getElement()); } private Element createScopeVariablesPane() { return createExpandablePane("Scope Variables", "Not paused", "", scopeVariablesPaneView.getElement()); } private Element createBreakpointsPane() { return createExpandablePane("Breakpoints", "No breakpoints", "", breakpointsPaneView.getElement()); } private Element createDomInspectorPane() { return createExpandablePane("DOM Inspector", "Not paused", "", domInspectorView.getElement()); } private Element createConsolePane() { return createExpandablePane("Console", "Not debugging", "", consoleView.getElement()); } private Element createExpandablePane(String titleText, String infoHeader, String infoBody, Element dataElement) { Element pane = Elements.createDivElement(css.expandablePane()); Element title = Elements.createDivElement(css.paneTitle()); DomUtils.appendDivWithTextContent(title, css.paneTitleText(), titleText); title.addEventListener(Event.CLICK, expandCollapsePaneListener, false); Element info = Elements.createDivElement(css.paneInfo()); if (!StringUtils.isNullOrEmpty(infoHeader)) { DomUtils.appendDivWithTextContent(info, css.paneInfoHeader(), infoHeader); } if (!StringUtils.isNullOrEmpty(infoBody)) { DomUtils.appendDivWithTextContent(info, css.paneInfoBody(), infoBody); } Element data = Elements.createDivElement(css.paneData()); if (dataElement != null) { data.appendChild(dataElement); } Element body = Elements.createDivElement(css.paneBody()); body.appendChild(info); body.appendChild(data); pane.appendChild(title); pane.appendChild(body); return pane; } private Element getPaneTitle(Element pane) { return DomUtils.getFirstElementByClassName(pane, css.paneTitle()); } private void showPaneData(Element pane, boolean show) { Element info = DomUtils.getFirstElementByClassName(pane, css.paneInfo()); Element data = DomUtils.getFirstElementByClassName(pane, css.paneData()); CssUtils.setDisplayVisibility(info, !show); CssUtils.setDisplayVisibility(data, show); } private void expandPane(Element pane, boolean expand) { CssUtils.setClassNameEnabled(pane, css.paneExpanded(), expand); } private void showNoApiPane(boolean show) { CssUtils.setDisplayVisibility(headerPane, !show); CssUtils.setDisplayVisibility(controlsPane, !show); CssUtils.setDisplayVisibility(watchExpressionsPane, !show); CssUtils.setDisplayVisibility(callStackPane, !show); CssUtils.setDisplayVisibility(scopeVariablesPane, !show); // Breakpoints pane stays always visible. CssUtils.setDisplayVisibility(noApiPane, show); } } public static DebuggingSidebar create(Resources resources, DebuggerState debuggerState) { View view = new View(resources); DebuggingSidebarHeader header = DebuggingSidebarHeader.create(view.headerView); DebuggingSidebarControlsPane controlsPane = DebuggingSidebarControlsPane.create(view.controlsPaneView); DebuggingSidebarWatchExpressionsPane watchExpressionsPane = DebuggingSidebarWatchExpressionsPane.create(view.watchExpressionsPaneView, debuggerState); DebuggingSidebarCallStackPane callStackPane = DebuggingSidebarCallStackPane.create(view.callStackPaneView); DebuggingSidebarScopeVariablesPane scopeVariablesPane = DebuggingSidebarScopeVariablesPane.create(view.scopeVariablesPaneView, debuggerState); DebuggingSidebarBreakpointsPane breakpointsPane = DebuggingSidebarBreakpointsPane.create(view.breakpointsPaneView); DomInspector domInspector = DomInspector.create(view.domInspectorView, debuggerState); ConsoleView console = ConsoleView.create(view.consoleView, debuggerState); DebuggingSidebarNoApiPane noApiPane = DebuggingSidebarNoApiPane.create(view.noApiPaneView, debuggerState); return new DebuggingSidebar(view, header, controlsPane, watchExpressionsPane, callStackPane, scopeVariablesPane, breakpointsPane, domInspector, console, noApiPane); } private static final Dispatcher<DebuggerCommandListener> ON_ACTIVATE_BREAKPOINTS_DISPATCHER = new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { listener.onActivateBreakpoints(); } }; private static final Dispatcher<DebuggerCommandListener> ON_DEACTIVATE_BREAKPOINTS_DISPATCHER = new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { listener.onDeactivateBreakpoints(); } }; private final class ViewEventsImpl implements DebuggingSidebarHeader.Listener, DebuggingSidebarControlsPane.Listener, DebuggingSidebarWatchExpressionsPane.Listener, DebuggingSidebarCallStackPane.Listener, DebuggingSidebarBreakpointsPane.Listener, DebuggingSidebarNoApiPane.Listener, ConsoleView.Listener { @Override public void onDebuggerCommand(final DebuggingSidebarControlsPane.DebuggerCommand command) { commandListenerManager.dispatch(new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { switch (command) { case PAUSE: listener.onPause(); break; case RESUME: listener.onResume(); break; case STEP_OVER: listener.onStepOver(); break; case STEP_INTO: listener.onStepInto(); break; case STEP_OUT: listener.onStepOut(); break; } } }); } @Override public void onCallFrameSelect(final int depth) { commandListenerManager.dispatch(new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { listener.onCallFrameSelect(depth); } }); } @Override public void onBreakpointIconClick(final Breakpoint breakpoint) { commandListenerManager.dispatch(new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { listener.onBreakpointIconClick(breakpoint); } }); } @Override public void onBreakpointLineClick(final Breakpoint breakpoint) { commandListenerManager.dispatch(new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { listener.onBreakpointLineClick(breakpoint); } }); } @Override public void onActivateBreakpoints() { commandListenerManager.dispatch(ON_ACTIVATE_BREAKPOINTS_DISPATCHER); } @Override public void onDeactivateBreakpoints() { commandListenerManager.dispatch(ON_DEACTIVATE_BREAKPOINTS_DISPATCHER); } @Override public void onBeforeAddWatchExpression() { // Show the Watch Expressions pane tree. getView().expandPane(getView().watchExpressionsPane, true); getView().showPaneData(getView().watchExpressionsPane, true); } @Override public void onWatchExpressionsCountChange() { updateWatchExpressionsPaneState(); } @Override public void onShouldDisplayNoApiPaneChange() { getView().showNoApiPane(noApiPane.shouldDisplay()); } @Override public void onLocationLinkClick(final String url, final int lineNumber) { commandListenerManager.dispatch(new Dispatcher<DebuggerCommandListener>() { @Override public void dispatch(DebuggerCommandListener listener) { listener.onLocationLinkClick(url, lineNumber); } }); } } private final ListenerManager<DebuggerCommandListener> commandListenerManager; private final DebuggingSidebarHeader header; private final DebuggingSidebarControlsPane controlsPane; private final DebuggingSidebarWatchExpressionsPane watchExpressionsPane; private final DebuggingSidebarCallStackPane callStackPane; private final DebuggingSidebarScopeVariablesPane scopeVariablesPane; private final DebuggingSidebarBreakpointsPane breakpointsPane; private final DomInspector domInspector; private final ConsoleView console; private final DebuggingSidebarNoApiPane noApiPane; private DebuggingSidebar(final View view, DebuggingSidebarHeader header, DebuggingSidebarControlsPane controlsPane, DebuggingSidebarWatchExpressionsPane watchExpressionsPane, DebuggingSidebarCallStackPane callStackPane, DebuggingSidebarScopeVariablesPane scopeVariablesPane, DebuggingSidebarBreakpointsPane breakpointsPane, DomInspector domInspector, ConsoleView console, DebuggingSidebarNoApiPane noApiPane) { super(view); this.commandListenerManager = ListenerManager.create(); this.header = header; this.controlsPane = controlsPane; this.watchExpressionsPane = watchExpressionsPane; this.callStackPane = callStackPane; this.scopeVariablesPane = scopeVariablesPane; this.breakpointsPane = breakpointsPane; this.domInspector = domInspector; this.console = console; this.noApiPane = noApiPane; watchExpressionsPane.attachControlButtons( getView().getPaneTitle(getView().watchExpressionsPane)); ViewEventsImpl delegate = new ViewEventsImpl(); header.setListener(delegate); controlsPane.setListener(delegate); watchExpressionsPane.setListener(delegate); callStackPane.setListener(delegate); breakpointsPane.setListener(delegate); noApiPane.setListener(delegate); console.setListener(delegate); // Initialize the UI with the defaults. setActive(false); setPaused(false); setAllBreakpointsActive(true); setScopeVariablesRootNodes(null); refreshWatchExpressions(); // Expand some panes. getView().expandPane(getView().callStackPane, true); getView().expandPane(getView().scopeVariablesPane, true); getView().expandPane(getView().breakpointsPane, true); getView().expandPane(getView().consolePane, true); getView().showNoApiPane(noApiPane.shouldDisplay()); } public void setActive(boolean active) { controlsPane.setActive(active); if (active) { domInspector.show(); console.show(); } else { domInspector.hide(); console.hide(); } getView().showPaneData(getView().domInspectorPane, active); getView().showPaneData(getView().consolePane, active); } public void setPaused(boolean paused) { controlsPane.setPaused(paused); } public void setAllBreakpointsActive(boolean active) { header.setAllBreakpointsActive(active); } public void clearCallStack() { callStackPane.clearCallStack(); getView().showPaneData(getView().callStackPane, false); } public void addCallFrame(String title, String subtitle) { getView().showPaneData(getView().callStackPane, true); callStackPane.addCallFrame(title, subtitle); } public void addBreakpoint(Breakpoint breakpoint) { if (breakpointsPane.hasBreakpoint(breakpoint)) { return; } breakpointsPane.addBreakpoint(breakpoint); updateBreakpointsPaneState(); // If added a first breakpoint, expand the breakpoint pane automatically. if (breakpointsPane.getBreakpointCount() == 1) { getView().expandPane(getView().breakpointsPane, true); } } public void removeBreakpoint(Breakpoint breakpoint) { breakpointsPane.removeBreakpoint(breakpoint); updateBreakpointsPaneState(); } public void updateBreakpoint(Breakpoint breakpoint, String line) { addBreakpoint(breakpoint); // Adds if absent. breakpointsPane.updateBreakpoint(breakpoint, line); } public String getBreakpointLineText(Breakpoint breakpoint) { return breakpointsPane.getBreakpointLineText(breakpoint); } private void updateBreakpointsPaneState() { boolean hasBreakpoints = breakpointsPane.getBreakpointCount() > 0; getView().showPaneData(getView().breakpointsPane, hasBreakpoints); } public void setScopeVariablesRootNodes(@Nullable JsonArray<RemoteObjectNode> rootNodes) { scopeVariablesPane.setScopeVariablesRootNodes(rootNodes); getView().showPaneData(getView().scopeVariablesPane, rootNodes != null); } public void refreshWatchExpressions() { watchExpressionsPane.refreshWatchExpressions(); updateWatchExpressionsPaneState(); } private void updateWatchExpressionsPaneState() { boolean hasWatchExpressions = watchExpressionsPane.getExpressionsCount() > 0; getView().showPaneData(getView().watchExpressionsPane, hasWatchExpressions); } public ListenerRegistrar<DebuggerCommandListener> getDebuggerCommandListenerRegistrar() { return commandListenerManager; } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggingSidebarScopeVariablesPane.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggingSidebarScopeVariablesPane.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 collide.client.util.Elements; import com.google.collide.json.shared.JsonArray; 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; /** * Scope variables pane in the debugging sidebar. */ public class DebuggingSidebarScopeVariablesPane extends UiComponent< DebuggingSidebarScopeVariablesPane.View> { public interface Css extends CssResource { String root(); } interface Resources extends ClientBundle, RemoteObjectTree.Resources { @Source("DebuggingSidebarScopeVariablesPane.css") Css workspaceEditorDebuggingSidebarScopeVariablesPaneCss(); } /** * The view for the scope variables pane. */ static class View extends CompositeView<Void> { private final Resources resources; private final Css css; private final RemoteObjectTree.View treeView; View(Resources resources) { this.resources = resources; css = resources.workspaceEditorDebuggingSidebarScopeVariablesPaneCss(); treeView = new RemoteObjectTree.View(resources); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(treeView.getElement()); setElement(rootElement); } } static DebuggingSidebarScopeVariablesPane create(View view, DebuggerState debuggerState) { RemoteObjectTree tree = RemoteObjectTree.create(view.treeView, view.resources, debuggerState); return new DebuggingSidebarScopeVariablesPane(view, tree); } private final RemoteObjectTree tree; @VisibleForTesting DebuggingSidebarScopeVariablesPane(View view, RemoteObjectTree tree) { super(view); this.tree = tree; } void setScopeVariablesRootNodes(@Nullable JsonArray<RemoteObjectNode> rootNodes) { if (rootNodes == null) { tree.setRoot(null); return; } RemoteObjectNode newRootNode = RemoteObjectNode.createRoot(); for (int i = 0, n = rootNodes.size(); i < n; ++i) { newRootNode.addChild(rootNodes.get(i)); } tree.setRoot(newRootNode); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/RemoteObjectTree.java
client/src/main/java/com/google/collide/client/code/debugging/RemoteObjectTree.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 collide.client.treeview.Tree; import collide.client.treeview.TreeNodeElement; import collide.client.treeview.TreeNodeLabelRenamer; import collide.client.treeview.TreeNodeMutator; import collide.client.util.Elements; import com.google.collide.client.code.debugging.DebuggerApiTypes.OnEvaluateExpressionResponse; 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.PropertyDescriptor; import com.google.collide.client.code.debugging.DebuggerApiTypes.RemoteObject; import com.google.collide.client.ui.dropdown.DropdownWidgets; import com.google.collide.client.util.AnimationUtils; import com.google.collide.json.shared.JsonArray; import com.google.collide.json.shared.JsonStringMap; 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.ListenerRegistrar; 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.user.client.Timer; import elemental.css.CSSStyleDeclaration; import elemental.dom.Element; import elemental.events.Event; import elemental.events.EventListener; import elemental.js.html.JsDragEvent; /** * Renders a {@link RemoteObject} in a tree-like UI. * */ public class RemoteObjectTree extends UiComponent<RemoteObjectTree.View> { public interface Css extends CssResource, TreeNodeMutator.Css { String root(); @Override String nodeNameInput(); } interface Resources extends DropdownWidgets.Resources, ClientBundle, Tree.Resources, RemoteObjectNodeRenderer.Resources { @Source("RemoteObjectTree.css") Css remoteObjectTreeCss(); } /** * The view for the remote object tree. */ static class View extends CompositeView<ViewEvents> { private final Css css; private final Tree.View<RemoteObjectNode> treeView; private final EventListener dblClickListener = new EventListener() { @Override public void handleEvent(Event evt) { Element target = (Element) evt.getTarget(); if (getDelegate().onDblClick(target)) { evt.stopPropagation(); } } }; private final EventListener scrollListener = new EventListener() { @Override public void handleEvent(Event evt) { // Ensure scrollLeft is always zero (we do not support horizontal scrolling). getElement().setScrollLeft(0); } }; View(Resources resources) { css = resources.remoteObjectTreeCss(); treeView = new Tree.View<RemoteObjectNode>(resources); Element rootElement = Elements.createDivElement(css.root()); rootElement.appendChild(treeView.getElement()); rootElement.addEventListener(Event.DBLCLICK, dblClickListener, false); rootElement.addEventListener(Event.SCROLL, scrollListener, false); setElement(rootElement); } } /** * User actions on the debugger. */ public interface Listener { void onRootChildrenChanged(); } /** * The view events. */ private interface ViewEvents { boolean onDblClick(Element target); } static RemoteObjectTree create(View view, Resources resources, DebuggerState debuggerState) { RemoteObjectNodeDataAdapter nodeDataAdapter = new RemoteObjectNodeDataAdapter(); RemoteObjectNodeRenderer nodeRenderer = new RemoteObjectNodeRenderer(resources); Tree<RemoteObjectNode> tree = Tree.create(view.treeView, nodeDataAdapter, nodeRenderer, resources); TreeNodeLabelRenamer<RemoteObjectNode> nodeLabelMutator = new TreeNodeLabelRenamer<RemoteObjectNode>( nodeRenderer, nodeDataAdapter, resources.remoteObjectTreeCss()); RemoteObjectTreeContextMenuController contextMenuController = RemoteObjectTreeContextMenuController.create( resources, debuggerState, nodeRenderer, nodeLabelMutator); return new RemoteObjectTree( view, tree, nodeRenderer, nodeLabelMutator, debuggerState, contextMenuController); } private static final int MAX_NUMBER_OF_CACHED_PATHS = 50; private final Tree<RemoteObjectNode> tree; private final TreeNodeLabelRenamer<RemoteObjectNode> nodeLabelMutator; private final RemoteObjectNodeRenderer nodeRenderer; private final DebuggerState debuggerState; private final RemoteObjectTreeContextMenuController contextMenuController; private Listener listener; private RemoteObjectNodeCache remoteObjectNodes = new RemoteObjectNodeCache(); private JsonArray<JsonArray<String>> pathsToExpand = JsonCollections.createArray(); private JsonStringMap<String> deferredEvaluations = JsonCollections.createMap(); private RemoteObjectNode recentEditedNode; private final Tree.Listener<RemoteObjectNode> treeListener = new Tree.Listener<RemoteObjectNode>() { @Override public void onNodeAction(TreeNodeElement<RemoteObjectNode> node) { } @Override public void onNodeClosed(TreeNodeElement<RemoteObjectNode> node) { } @Override public void onNodeContextMenu(int mouseX, int mouseY, TreeNodeElement<RemoteObjectNode> node) { contextMenuController.show(mouseX, mouseY, node); } @Override public void onNodeDragDrop(TreeNodeElement<RemoteObjectNode> node, JsDragEvent event) { } @Override public void onRootDragDrop(JsDragEvent event) { } @Override public void onNodeExpanded(TreeNodeElement<RemoteObjectNode> node) { RemoteObjectNode remoteObjectNode = node.getData(); if (remoteObjectNode.shouldRequestChildren()) { debuggerState.requestRemoteObjectProperties( remoteObjectNode.getRemoteObject().getObjectId()); } } @Override public void onRootContextMenu(int mouseX, int mouseY) { } @Override public void onNodeDragStart(TreeNodeElement<RemoteObjectNode> node, JsDragEvent event) { } }; private final TreeNodeLabelRenamer.LabelRenamerCallback<RemoteObjectNode> addNewNodeCallback = new TreeNodeLabelRenamer.LabelRenamerCallback<RemoteObjectNode>() { @Override public void onCommit(String oldLabel, TreeNodeElement<RemoteObjectNode> node) { handleOnAddNewNode(node); } @Override public boolean passValidation(TreeNodeElement<RemoteObjectNode> node, String newLabel) { return true; } }; private class DebuggerListenerImpl implements DebuggerState.RemoteObjectListener, DebuggerState.DebuggerStateListener, DebuggerState.EvaluateExpressionListener { @Override public void onDebuggerStateChange() { if (!debuggerState.isActive()) { // Prevent memory leaks. pathsToExpand.clear(); deferredEvaluations = JsonCollections.createMap(); } } @Override public void onRemoteObjectPropertiesResponse(OnRemoteObjectPropertiesResponse response) { handleOnRemoteObjectPropertiesResponse(response); } @Override public void onRemoteObjectPropertyChanged(OnRemoteObjectPropertyChanged response) { handleOnRemoteObjectPropertyChanged(response); } @Override public void onEvaluateExpressionResponse(OnEvaluateExpressionResponse response) { handleOnEvaluateExpressionResponse(response); } @Override public void onGlobalObjectChanged() { reevaluateRootChildren(); } } private final DebuggerListenerImpl debuggerListener = new DebuggerListenerImpl(); private final Timer treeHeightRestorer = new Timer() { @Override public void run() { AnimationUtils.animatePropertySet(getView().getElement(), "min-height", "0px", AnimationUtils.SHORT_TRANSITION_DURATION); } }; private final ListenerRegistrar.RemoverManager removerManager = new ListenerRegistrar.RemoverManager(); private RemoteObjectTree(View view, Tree<RemoteObjectNode> tree, RemoteObjectNodeRenderer nodeRenderer, TreeNodeLabelRenamer<RemoteObjectNode> nodeLabelMutator, DebuggerState debuggerState, RemoteObjectTreeContextMenuController contextMenuController) { super(view); this.tree = tree; this.nodeRenderer = nodeRenderer; this.nodeLabelMutator = nodeLabelMutator; this.debuggerState = debuggerState; this.contextMenuController = contextMenuController; removerManager .track(debuggerState.getRemoteObjectListenerRegistrar().add(debuggerListener)) .track(debuggerState.getDebuggerStateListenerRegistrar().add(debuggerListener)) .track(debuggerState.getEvaluateExpressionListenerRegistrar().add(debuggerListener)); tree.setTreeEventHandler(treeListener); setContextMenuEventListener(); view.setDelegate(new ViewEvents() { @Override public boolean onDblClick(Element target) { return handleOnDblClick(target); } }); } private void setContextMenuEventListener() { contextMenuController.setListener(new RemoteObjectTreeContextMenuController.Listener() { @Override public void onAddNewChild(TreeNodeElement<RemoteObjectNode> nodeElement) { // Expand the node if collapsed. tree.expandNode(nodeElement); treeListener.onNodeExpanded(nodeElement); addMutableChild(nodeElement.getData()); } @Override public void onNodeEdited(TreeNodeElement<RemoteObjectNode> nodeElement, String newLabel) { // Collapse the node if expanded. tree.closeNode(nodeElement); RemoteObjectNode node = nodeElement.getData(); RemoteObjectNode parent = node.getParent(); if (node.isRootChild()) { String expression = "(" + node.getName() + ") = (" + newLabel + ")"; // After this is executed we need to re-evaluate the original watch expression. deferredEvaluations.put(expression, node.getName()); debuggerState.evaluateExpression(expression); } else if (parent != null && parent.getRemoteObject() != null) { // We do not know the new token type, so just remove the old one for the // time being (i.e. until we get the answer from the debugger). nodeRenderer.removeTokenClassName(node, nodeElement.getNodeLabel()); recentEditedNode = node; debuggerState.setRemoteObjectProperty( parent.getRemoteObject().getObjectId(), node.getName(), newLabel); } } @Override public void onNodeDeleted(TreeNodeElement<RemoteObjectNode> nodeElement) { RemoteObjectNode node = nodeElement.getData(); RemoteObjectNode parent = node.getParent(); JsonArray<RemoteObjectNode> selectedNodes = tree.getSelectionModel().getSelectedNodes(); if (node.isRootChild()) { for (int i = 0, n = selectedNodes.size(); i < n; ++i) { RemoteObjectNode selectedNode = selectedNodes.get(i); if (selectedNode.isRootChild() && selectedNode.getParent() == parent) { parent.removeChild(selectedNode); } } // Repaint the sub-tree. replaceRemoteObjectNode(parent, parent); } else if (parent != null && parent.getRemoteObject() != null) { for (int i = 0, n = selectedNodes.size(); i < n; ++i) { RemoteObjectNode selectedNode = selectedNodes.get(i); if (selectedNode.getParent() == parent) { recentEditedNode = null; debuggerState.removeRemoteObjectProperty( parent.getRemoteObject().getObjectId(), selectedNode.getName()); } } } } @Override public void onNodeRenamed(TreeNodeElement<RemoteObjectNode> nodeElement, String oldLabel) { RemoteObjectNode node = nodeElement.getData(); RemoteObjectNode parent = node.getParent(); if (node.isRootChild()) { debuggerState.evaluateExpression(node.getName()); } else if (parent != null && parent.getRemoteObject() != null) { String newLabel = node.getName(); // Undo renaming until we get the answer from the debugger. nodeLabelMutator.mutateNodeKey(nodeElement, oldLabel); recentEditedNode = node; debuggerState.renameRemoteObjectProperty( parent.getRemoteObject().getObjectId(), oldLabel, newLabel); } } }); } void teardown() { removerManager.remove(); tree.setTreeEventHandler(null); contextMenuController.setListener(null); setRoot(null); // Also clears the RemoteObjectNodeCache. setListener(null); pathsToExpand.clear(); deferredEvaluations = JsonCollections.createMap(); recentEditedNode = null; } void setListener(Listener listener) { this.listener = listener; } /** * Returns the root of the tree. Also commits all active mutations, so that * the tree should not be in an inconsistent state while exposing it's root * outside. * * @return tree root */ RemoteObjectNode getRoot() { nodeLabelMutator.forceCommit(); return tree.getModel().getRoot(); } int getRootChildrenCount() { RemoteObjectNode root = tree.getModel().getRoot(); if (root == null) { return 0; } return root.getChildren().size(); } void setRoot(@Nullable RemoteObjectNode newRoot) { RemoteObjectNode root = tree.getModel().getRoot(); if (root != newRoot) { recentEditedNode = null; } replaceRemoteObjectNode(root, newRoot); } Element getContextMenuElement() { return contextMenuController.getContextMenuElement(); } /** * Replaces an existing {@link RemoteObjectNode} with a new one, and refreshes * the tree UI. This will also save the changes to the {@link RemoteObjectNode} * model. * * @param oldNode old node to be removed * @param newNode new node to replace the old one */ void replaceRemoteObjectNode(RemoteObjectNode oldNode, RemoteObjectNode newNode) { contextMenuController.hide(); // Save the changes to the model. if (oldNode != newNode && oldNode != null) { RemoteObjectNode parent = oldNode.getParent(); if (parent != null) { parent.removeChild(oldNode); if (newNode != null) { parent.addChild(newNode); } } } saveTreeMinHeight(); // NOTE: Update the UI before tearing down the cache. pathsToExpand.addAll(tree.replaceSubtree(oldNode, newNode, false)); replaceRemoteObjectNodesCache(collectAllChildren()); expandCachedPaths(); if (listener != null && newNode == tree.getModel().getRoot()) { listener.onRootChildrenChanged(); } } private void expandCachedPaths() { pathsToExpand = tree.expandPaths(pathsToExpand, true); // Ensure maximum size of the cache. if (pathsToExpand.size() > MAX_NUMBER_OF_CACHED_PATHS) { pathsToExpand.splice(0, pathsToExpand.size() - MAX_NUMBER_OF_CACHED_PATHS); } } private void removeRemoteObjectNode(RemoteObjectNode node) { contextMenuController.hide(); // Save the changes to the model. RemoteObjectNode parent = node.getParent(); if (parent != null) { parent.removeChild(node); } // Update the tree UI. tree.removeNode(node.getRenderedTreeNode()); remoteObjectNodes.remove(node); node.teardown(); if (listener != null && parent == tree.getModel().getRoot()) { listener.onRootChildrenChanged(); } } private void saveTreeMinHeight() { Element element = getView().getElement(); AnimationUtils.removeTransitions(element.getStyle()); element.getStyle().setProperty("min-height", element.getOffsetHeight() + CSSStyleDeclaration.Unit.PX); treeHeightRestorer.schedule(100); } void collapseRootChildren() { RemoteObjectNode root = tree.getModel().getRoot(); if (root == null) { return; } JsonArray<RemoteObjectNode> children = root.getChildren(); for (int i = 0, n = children.size(); i < n; ++i) { TreeNodeElement<RemoteObjectNode> nodeElement = tree.getModel().getDataAdapter().getRenderedTreeNode(children.get(i)); if (nodeElement != null) { tree.closeNode(nodeElement); } } } void addMutableRootChild() { if (nodeLabelMutator.isMutating()) { return; } RemoteObjectNode root = tree.getModel().getRoot(); if (root == null) { root = RemoteObjectNode.createRoot(); setRoot(root); } addMutableChild(root); } private void addMutableChild(RemoteObjectNode parent) { RemoteObjectNode child = RemoteObjectNode.createBeingEdited(); if (hasNoRealRemoteObjectChildren(parent)) { // Handle the case when there is only a dummy "No Properties" node. replaceRemoteObjectNode(parent.getChildren().get(0), child); } else { parent.addChild(child); replaceRemoteObjectNode(parent, parent); } nodeLabelMutator.cancel(); nodeLabelMutator.enterMutation(tree.getModel().getDataAdapter().getRenderedTreeNode(child), addNewNodeCallback); } private void handleOnAddNewNode(TreeNodeElement<RemoteObjectNode> nodeElement) { RemoteObjectNode node = nodeElement.getData(); RemoteObjectNode parent = node.getParent(); String name = node.getName(); boolean isRootChild = node.isRootChild(); recentEditedNode = parent; removeRemoteObjectNode(node); if (isRootChild) { appendRootChild(name); } else if (parent != null && parent.getRemoteObject() != null && !StringUtils.isNullOrWhitespace(name)) { RemoteObjectNode newChild = parent.getFirstChildByName(name); if (newChild == null) { // Tell the debugger to add the new property to the remote object and wait for response. debuggerState.setRemoteObjectProperty(parent.getRemoteObject().getObjectId(), name, DebuggerApiTypes.UNDEFINED_REMOTE_OBJECT.getDescription()); } else if (!nodeLabelMutator.isMutating() && newChild.getRenderedTreeNode() != null) { contextMenuController.enterEditPropertyValue(newChild.getRenderedTreeNode()); } } else if (hasNoRealRemoteObjectChildren(parent)) { // We should probably render the dummy "No Properties" element again. replaceRemoteObjectNode(parent, parent); } } /** * @return true if the given node has only the dummy "No Properties" child */ private static boolean hasNoRealRemoteObjectChildren(RemoteObjectNode node) { JsonArray<RemoteObjectNode> children = node.getChildren(); return (children.size() == 1 && children.get(0).getRemoteObject() == null); } private void handleOnRemoteObjectPropertiesResponse(OnRemoteObjectPropertiesResponse response) { JsonArray<RemoteObjectNode> parentNodes = remoteObjectNodes.get(response.getObjectId()); if (parentNodes == null) { return; } for (int i = 0, n = parentNodes.size(); i < n; ++i) { handleOnRemoteObjectPropertiesResponse(response, parentNodes.get(i)); } expandCachedPaths(); // Re-schedule the treeHeightRestorer timer. saveTreeMinHeight(); if (recentEditedNode != null) { // A user may have been in the process of adding a new property, but was unable to do so // until we fetch all properties of the remote object from the debugger. for (int i = 0, n = parentNodes.size(); i < n; ++i) { RemoteObjectNode parentNode = parentNodes.get(i); if (parentNode == recentEditedNode) { recentEditedNode = null; if (!nodeLabelMutator.isMutating()) { addMutableChild(parentNode); } break; } } } } private void handleOnRemoteObjectPropertiesResponse(OnRemoteObjectPropertiesResponse response, RemoteObjectNode parentNode) { if (!parentNode.shouldRequestChildren()) { // We already processed a request for this node. return; } JsonArray<PropertyDescriptor> properties = response.getProperties(); for (int i = 0, n = properties.size(); i < n; ++i) { PropertyDescriptor property = properties.get(i); boolean isGetterOrSetter = (property.getGetterFunction() != null || property.getSetterFunction() != null); if (isGetterOrSetter) { if (property.getGetterFunction() != null) { RemoteObjectNode child = RemoteObjectNode.createGetterProperty( property.getName(), property.getGetterFunction()); appendNewNode(parentNode, child); } if (property.getSetterFunction() != null) { RemoteObjectNode child = RemoteObjectNode.createSetterProperty( property.getName(), property.getSetterFunction()); appendNewNode(parentNode, child); } } else if (property.getValue() != null) { RemoteObjectNode child = new RemoteObjectNode.Builder(property.getName(), property.getValue()) .setWasThrown(property.wasThrown()) .setDeletable(property.isConfigurable()) .setWritable(property.isWritable()) .setEnumerable(property.isEnumerable()) .build(); appendNewNode(parentNode, child); } } parentNode.setAllChildrenRequested(); // Repaint the node. pathsToExpand.addAll(tree.replaceSubtree(parentNode, parentNode, false)); } private void appendNewNode(RemoteObjectNode parent, RemoteObjectNode child) { remoteObjectNodes.put(child); parent.addChild(child); } private void handleOnRemoteObjectPropertyChanged(OnRemoteObjectPropertyChanged response) { JsonArray<RemoteObjectNode> parentNodes = remoteObjectNodes.get(response.getObjectId()); if (parentNodes == null) { return; } boolean shouldRefreshProperties = (response.wasThrown() || (response.isValueChanged() && response.getValue() == null)); for (int i = 0, n = parentNodes.size(); i < n; ++i) { RemoteObjectNode parent = parentNodes.get(i); if (shouldRefreshProperties) { // Just refresh all properties of this object. if (parent == recentEditedNode) { recentEditedNode = null; } RemoteObjectNode newParent = new RemoteObjectNode.Builder(parent.getName(), parent.getRemoteObject(), parent) .build(); replaceRemoteObjectNode(parent, newParent); continue; } RemoteObjectNode child = parent.getFirstChildByName(response.getOldName()); if (child == null) { // A new property was added. if (response.getNewName() != null) { RemoteObjectNode newChild = new RemoteObjectNode.Builder(response.getNewName(), response.getValue()).build(); parent.addChild(newChild); replaceRemoteObjectNode(parent, parent); // Continue adding a new property with editing it's value. if (parent == recentEditedNode) { recentEditedNode = null; if (!nodeLabelMutator.isMutating() && newChild.getRenderedTreeNode() != null) { contextMenuController.enterEditPropertyValue(newChild.getRenderedTreeNode()); } } } } else if (response.getNewName() == null) { // The property was removed. removeRemoteObjectNode(child); } else { RemoteObject newValue = response.isValueChanged() ? response.getValue() : child.getRemoteObject(); RemoteObjectNode newChild = new RemoteObjectNode.Builder(response.getNewName(), newValue, child).build(); // We could be replacing onto an existing child. If so, delete it first. if (!StringUtils.equalNonEmptyStrings(response.getOldName(), response.getNewName())) { RemoteObjectNode oldNewChild = parent.getFirstChildByName(response.getNewName()); if (oldNewChild != null) { removeRemoteObjectNode(oldNewChild); } } replaceRemoteObjectNode(child, newChild); // Collapse the selection to the recently edited node. if (child == recentEditedNode) { recentEditedNode = null; tree.getSelectionModel().selectSingleNode(newChild); } } } } private void replaceRemoteObjectNodesCache(final RemoteObjectNodeCache newCache) { // Tear down objects from the old cache first. remoteObjectNodes.iterate(new RemoteObjectNodeCache.IterationCallback() { @Override public void onIteration(String key, JsonArray<RemoteObjectNode> values) { for (int i = 0, n = values.size(); i < n; ++i) { RemoteObjectNode node = values.get(i); if (!newCache.contains(node)) { node.teardown(); } } } }); remoteObjectNodes = newCache; } private RemoteObjectNodeCache collectAllChildren() { final RemoteObjectNodeCache result = new RemoteObjectNodeCache(); RemoteObjectNode root = tree.getModel().getRoot(); if (root != null) { Tree.iterateDfs(root, tree.getModel().getDataAdapter(), new Tree.Visitor<RemoteObjectNode>() { @Override public boolean shouldVisit(RemoteObjectNode node) { return true; // Visit all nodes. } @Override public void visit(RemoteObjectNode node, boolean willVisitChildren) { result.put(node); } }); } return result; } private boolean handleOnDblClick(Element target) { TreeNodeElement<RemoteObjectNode> nodeElement = tree.getNodeFromElement(target); if (nodeElement == null) { return false; } RemoteObjectNode node = nodeElement.getData(); if (node.hasChildren()) { // The default DblClick will expand/collapse the node. return false; } if (nodeRenderer.getAncestorPropertyNameElement(target) != null) { return contextMenuController.enterRenameProperty(nodeElement); } else if (nodeRenderer.getAncestorPropertyValueElement(target) != null) { return contextMenuController.enterEditPropertyValue(nodeElement); } return false; } private void handleOnEvaluateExpressionResponse(OnEvaluateExpressionResponse response) { RemoteObjectNode root = tree.getModel().getRoot(); if (root == null) { return; } String expression = response.getExpression(); RemoteObject result = response.getResult(); JsonArray<RemoteObjectNode> children = root.getChildren(); for (int i = 0, n = children.size(); i < n; ++i) { RemoteObjectNode child = children.get(i); if (!child.isTransient() && child.getName().equals(expression)) { RemoteObjectNode newChild = new RemoteObjectNode.Builder(expression, result, child) .setWasThrown(response.wasThrown()) .build(); // Repaint the subtree. replaceRemoteObjectNode(child, newChild); } } String deferredExpression = deferredEvaluations.remove(expression); if (!StringUtils.isNullOrEmpty(deferredExpression)) { debuggerState.evaluateExpression(deferredExpression); } } void reevaluateRootChildren() { // Clear cached data (we are about to refresh everything anyway). deferredEvaluations = JsonCollections.createMap(); RemoteObjectNode root = tree.getModel().getRoot(); if (root == null) { // Nothing to do. return; } JsonArray<RemoteObjectNode> children = root.getChildren(); if (debuggerState.isActive()) { for (int i = 0, n = children.size(); i < n; ++i) { RemoteObjectNode child = children.get(i); if (!child.isTransient()) { debuggerState.evaluateExpression(child.getName()); } } } else { // Set all expressions' values undefined. RemoteObjectNode newRoot = RemoteObjectNode.createRoot(); for (int i = 0, n = children.size(); i < n; ++i) { RemoteObjectNode oldChild = children.get(i); RemoteObjectNode newChild = new RemoteObjectNode.Builder( oldChild.getName(), DebuggerApiTypes.UNDEFINED_REMOTE_OBJECT, oldChild).build(); newRoot.addChild(newChild); } setRoot(newRoot); } } private void appendRootChild(String expression) { String trimmedExpression = StringUtils.trimNullToEmpty(expression); if (StringUtils.isNullOrEmpty(trimmedExpression)) { return; } RemoteObjectNode root = tree.getModel().getRoot(); if (root == null) { root = RemoteObjectNode.createRoot(); } RemoteObjectNode lastChild = root.getLastChild(); RemoteObjectNode newChild = new RemoteObjectNode.Builder(trimmedExpression, DebuggerApiTypes.UNDEFINED_REMOTE_OBJECT) .setOrderIndex(lastChild == null ? 0 : lastChild.getOrderIndex() + 1) .build(); root.addChild(newChild); // Repaint the root. setRoot(root); debuggerState.evaluateExpression(trimmedExpression); } }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
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/DebuggerApiTypes.java
client/src/main/java/com/google/collide/client/code/debugging/DebuggerApiTypes.java
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.json.shared.JsonArray; /** * Defines data types used in the browser debugger API {@link DebuggerApi}. * * <p>The API design of these data types was inspired by the * <a href="http://code.google.com/chrome/devtools/docs/remote-debugging.html"> * Chrome DevTools Remote Debugging API</a>. */ class DebuggerApiTypes { public static final RemoteObject UNDEFINED_REMOTE_OBJECT = new RemoteObject() { @Override public String getDescription() { return "undefined"; } @Override public boolean hasChildren() { return false; } @Override public RemoteObjectId getObjectId() { return null; } @Override public RemoteObjectType getType() { return RemoteObjectType.UNDEFINED; } @Override public RemoteObjectSubType getSubType() { return null; } }; /** * Represents a breakpoint. */ public interface BreakpointInfo { /** * @return breakpoint's URL. Either {@link #getUrl} or {@link #getUrlRegex} * will be specified */ public String getUrl(); /** * @return a Regex pattern for the URLs of the resources to set breakpoints * on. Either {@link #getUrl} or {@link #getUrlRegex} will be * specified */ public String getUrlRegex(); /** * @return breakpoint's line number */ public int getLineNumber(); /** * @return breakpoint's column number */ public int getColumnNumber(); /** * @return breakpoint's condition */ public String getCondition(); } /** * Debugger response that is fired when a breakpoint is resolved. */ public interface OnBreakpointResolvedResponse { /** * @return breakpoint info */ public BreakpointInfo getBreakpointInfo(); /** * @return breakpoint unique identifier */ public String getBreakpointId(); /** * @return actual breakpoint locations. These may be many if, for example, * the script that contains the breakpoint is included more than * once into an application */ public JsonArray<Location> getLocations(); } /** * Debugger response that is fired when debugger stops execution. */ public interface OnPausedResponse { /** * @return call stack the debugger stopped on, so that the topmost call * frame is at index {@code 0} */ public JsonArray<CallFrame> getCallFrames(); } /** * Debugger response that is fired when debugger parses a script. */ public interface OnScriptParsedResponse { /** * @return line offset of the script within the resource with a given URL * (for script tags) */ public int getStartLine(); /** * @return column offset of the script within the resource with a given URL */ public int getStartColumn(); /** * @return last line of the script */ public int getEndLine(); /** * @return length of the last line of the script */ public int getEndColumn(); /** * @return URL of the script parsed (if any) */ public String getUrl(); /** * @return identifier of the parsed script */ public String getScriptId(); /** * @return whether this script is a user extension script (browser * extension's script, Grease Monkey script and etc.) */ public boolean isContentScript(); } /** * Debugger response that gives an array of properties of a remote object. */ public interface OnRemoteObjectPropertiesResponse { /** * @return unique object identifier of the {@link RemoteObject} */ public RemoteObjectId getObjectId(); /** * @return array of properties of the remote object */ public JsonArray<PropertyDescriptor> getProperties(); } /** * Debugger response that is fired when a property of a {@link RemoteObject} * was edited, renamed or deleted. */ public interface OnRemoteObjectPropertyChanged { /** * @return unique object identifier of the {@link RemoteObject} */ public RemoteObjectId getObjectId(); /** * @return old property name */ public String getOldName(); /** * @return new property name, or {@code null} if the property was deleted */ public String getNewName(); /** * @return true if property value has changed */ public boolean isValueChanged(); /** * @return property value if available, or {@code null} otherwise (in this * case it should be explicitly requested via the corresponding * Debugger API call, if needed) */ public RemoteObject getValue(); /** * @return true if an exception was thrown during the evaluation. In this * case the result of the corresponding remote call is undefined, * and it is recommended to request object properties again */ public boolean wasThrown(); } /** * Debugger response with the result of an evaluated expression. */ public interface OnEvaluateExpressionResponse { /** * @return the expression that was evaluated */ public String getExpression(); /** * @return ID of the {@link CallFrame} the expression was evaluated on, or * {@code null} if expression was evaluated on the global object */ public String getCallFrameId(); /** * @return evaluation result */ public RemoteObject getResult(); /** * @return true if an exception was thrown during the evaluation. In this * case the evaluation result will contain the thrown value */ public boolean wasThrown(); } /** * Debugger response with the metainfo about all known CSS stylesheets. */ public interface OnAllCssStyleSheetsResponse { /** * @return Descriptor headers for all available CSS stylesheets */ public JsonArray<CssStyleSheetHeader> getHeaders(); } /** * Represents a remote object in the context of debuggee application. * Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/runtime.html#type-RemoteObject * * <p>WARNING: If you modify this interface, also check out the * {@link DebuggerApiUtils#equal} method! */ public interface RemoteObject { /** * @return string representation of the object */ public String getDescription(); /** * @return true when this object can be queried for children */ public boolean hasChildren(); /** * @return unique object identifier for non-primitive values, * or {@code null} for primitive values */ public RemoteObjectId getObjectId(); /** * @return object type */ public RemoteObjectType getType(); /** * @return object subtype */ public RemoteObjectSubType getSubType(); } /** * Abstraction for the {@link RemoteObject} ID. */ public interface RemoteObjectId { /** * Returns a string representation of the {@link RemoteObject} ID. */ @Override public String toString(); } /** * Remote object's type. */ public enum RemoteObjectType { BOOLEAN, FUNCTION, NUMBER, OBJECT, STRING, UNDEFINED } /** * Remote object's subtype. Specified for {@link RemoteObjectType#OBJECT} * objects only. */ public enum RemoteObjectSubType { ARRAY, DATE, NODE, NULL, REGEXP } /** * Represents a property of a {@link RemoteObject}. * Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/runtime.html#type-PropertyDescriptor */ public interface PropertyDescriptor { /** * @return property name */ public String getName(); /** * @return property value, or the value that was thrown by an exception * if {@link #wasThrown} returns {@code true}, or {@code null} if * no value was associated with the property */ public RemoteObject getValue(); /** * @return true if an exception was thrown on the attempt to get the * property value. In this case the value property will contain * the thrown value */ public boolean wasThrown(); /** * @return true if the type of this property descriptor may be changed and * if the property may be deleted from the corresponding object */ public boolean isConfigurable(); /** * @return true if this property shows up during enumeration of the * properties on the corresponding object */ public boolean isEnumerable(); /** * @return true if the value associated with the property may be changed */ public boolean isWritable(); /** * @return a function which serves as a getter for the property, or * {@code null} if there is no getter */ public RemoteObject getGetterFunction(); /** * @return a function which serves as a setter for the property, or * {@code null} if there is no setter */ public RemoteObject getSetterFunction(); } /** * A call frame. Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/debugger.html#type-CallFrame */ public interface CallFrame { /** * @return name of the function called on this frame */ public String getFunctionName(); /** * @return call frame identifier */ public String getId(); /** * @return location in the source code */ public Location getLocation(); /** * @return scope chain for given call frame */ public JsonArray<Scope> getScopeChain(); /** * @return {@code this} object for this call frame */ public RemoteObject getThis(); } /** * An arbitrary location in a script. Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/debugger.html#type-Location */ public interface Location { /** * @return column number in the script */ public int getColumnNumber(); /** * @return line number in the script */ public int getLineNumber(); /** * @return script identifier as reported by the {@code scriptParsed} event */ public String getScriptId(); } /** * Represents JavaScript's scope. Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/debugger.html#type-Scope */ public interface Scope { /** * @return object representing the scope */ public RemoteObject getObject(); /** * @return true if the object representing the scope is an artificial * transient object used to enumerate the scope variables as its * properties, or false if it represents the actual object in the * Debugger VM */ public boolean isTransient(); /** * @return scope type */ public ScopeType getType(); } /** * JavaScript's scope type. */ public enum ScopeType { CATCH, CLOSURE, GLOBAL, LOCAL, WITH } /** * Pause on exceptions state. */ public enum PauseOnExceptionsState { ALL, NONE, UNCAUGHT } /** * Descriptor of a CSS stylesheet. Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/css.html#type-CSSStyleSheetHeader */ public interface CssStyleSheetHeader { /** * @return whether the stylesheet is disabled */ public boolean isDisabled(); /** * @return stylesheet ID */ public String getId(); /** * @return stylesheet resource URL */ public String getUrl(); /** * @return stylesheet title */ public String getTitle(); } /** * Represents a remote Console message. Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/console.html#type-ConsoleMessage */ public interface ConsoleMessage { /** * @return message severity level */ public ConsoleMessageLevel getLevel(); /** * @return Console API message type, or {@code null} if not appropriate * or not supported */ public ConsoleMessageType getType(); /** * @return line number in the resource that generated this message, * or {@code -1} if not appropriate */ public int getLineNumber(); /** * @return array of message parameters in case of a formatted message, or * empty array otherwise */ public JsonArray<RemoteObject> getParameters(); /** * @return repeat count for repeated messages, or {@code 1} for a single * message */ public int getRepeatCount(); /** * @return JavaScript stack trace for assertions and error messages, or * empty array if not appropriate */ public JsonArray<StackTraceItem> getStackTrace(); /** * @return message text */ public String getText(); /** * @return URL of the message origin, or {@code null} if not appropriate */ public String getUrl(); } /** * Console message severity level. */ public enum ConsoleMessageLevel { DEBUG, ERROR, LOG, TIP, WARNING } /** * Console message type. */ public enum ConsoleMessageType { ASSERT, DIR, DIRXML, ENDGROUP, LOG, STARTGROUP, STARTGROUPCOLLAPSED, TRACE } /** * Represents a remote JavaScript stack trace. Inspired by: * http://code.google.com/chrome/devtools/docs/protocol/tot/console.html#type-StackTrace */ public interface StackTraceItem { /** * @return JavaScript script column number */ public int getColumnNumber(); /** * @return JavaScript function name */ public String getFunctionName(); /** * @return JavaScript script line number */ public int getLineNumber(); /** * @return JavaScript script name or URL */ public String getUrl(); } private DebuggerApiTypes() {} // COV_NF_LINE }
java
Apache-2.0
2136cfc9705a96d88c69356868dda5b95c35bc6d
2026-01-05T02:34:36.415338Z
false