Search in sources :

Example 6 with LineWidget

use of org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget in project rstudio by rstudio.

the class PinnedLineWidget method checkForRemoval.

private boolean checkForRemoval() {
    LineWidget w = display_.getLineWidgetForRow(lineWidget_.getRow());
    if (w == null) {
        // ensure widget is detached
        widget_.getElement().removeFromParent();
        detachAnchors();
        if (host_ != null)
            host_.onLineWidgetRemoved(lineWidget_);
        return true;
    }
    return false;
}
Also used : LineWidget(org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget)

Example 7 with LineWidget

use of org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget in project rstudio by rstudio.

the class ImagePreviewer method onPreviewImageLineWidget.

private static void onPreviewImageLineWidget(final DocDisplay display, final DocUpdateSentinel sentinel, final String href, final String attributes, final Position position, final Range tokenRange) {
    // if we already have a line widget for this row, bail
    LineWidget lineWidget = display.getLineWidgetForRow(position.getRow());
    if (lineWidget != null)
        return;
    // shared mutable state that we hide in this closure
    final Mutable<PinnedLineWidget> plw = new Mutable<PinnedLineWidget>();
    final Mutable<ChunkOutputWidget> cow = new Mutable<ChunkOutputWidget>();
    final Mutable<HandlerRegistration> docChangedHandler = new Mutable<HandlerRegistration>();
    final Mutable<HandlerRegistration> renderHandler = new Mutable<HandlerRegistration>();
    // command that ensures state is cleaned up when widget hidden
    final Command onDetach = new Command() {

        private void detach() {
            // detach chunk output widget
            cow.set(null);
            // detach pinned line widget
            if (plw.get() != null)
                plw.get().detach();
            plw.set(null);
            // detach render handler
            if (renderHandler.get() != null)
                renderHandler.get().removeHandler();
            renderHandler.set(null);
            // detach doc changed handler
            if (docChangedHandler.get() != null)
                docChangedHandler.get().removeHandler();
            docChangedHandler.set(null);
        }

        @Override
        public void execute() {
            // if the associated chunk output widget has been cleaned up,
            // make a last-ditch detach effort anyhow
            ChunkOutputWidget widget = cow.get();
            if (widget == null) {
                detach();
                return;
            }
            // fade out and then detach
            FadeOutAnimation anim = new FadeOutAnimation(widget, new Command() {

                @Override
                public void execute() {
                    detach();
                }
            });
            anim.run(400);
        }
    };
    // construct placeholder for image
    final SimplePanel container = new SimplePanel();
    container.addStyleName(RES.styles().container());
    final Label noImageLabel = new Label("(No image at path " + href + ")");
    // resize command (used by various routines that need to respond
    // to width / height change events)
    final CommandWithArg<Integer> onResize = new CommandWithArg<Integer>() {

        private int state_ = -1;

        @Override
        public void execute(Integer height) {
            // defend against missing chunk output widget (can happen if a widget
            // is closed / dismissed before image finishes loading)
            ChunkOutputWidget widget = cow.get();
            if (widget == null)
                return;
            // don't resize if the chunk widget if we were already collapsed
            int state = widget.getExpansionState();
            if (state == state_ && state == ChunkOutputWidget.COLLAPSED)
                return;
            state_ = state;
            widget.getFrame().setHeight(height + "px");
            LineWidget lw = plw.get().getLineWidget();
            lw.setPixelHeight(height);
            display.onLineWidgetChanged(lw);
        }
    };
    // construct our image
    String srcPath = imgSrcPathFromHref(sentinel, href);
    final Image image = new Image(srcPath);
    image.addStyleName(RES.styles().image());
    // parse and inject attributes
    Map<String, String> parsedAttributes = HTMLAttributesParser.parseAttributes(attributes);
    final Element imgEl = image.getElement();
    for (Map.Entry<String, String> entry : parsedAttributes.entrySet()) {
        String key = entry.getKey();
        String val = entry.getValue();
        if (StringUtil.isNullOrEmpty(key) || StringUtil.isNullOrEmpty(val))
            continue;
        imgEl.setAttribute(key, val);
    }
    // add load handlers to image
    DOM.sinkEvents(imgEl, Event.ONLOAD | Event.ONERROR);
    DOM.setEventListener(imgEl, new EventListener() {

        @Override
        public void onBrowserEvent(Event event) {
            if (DOM.eventGetType(event) == Event.ONLOAD) {
                final ImageElementEx imgEl = image.getElement().cast();
                int minWidth = Math.min(imgEl.naturalWidth(), 100);
                int maxWidth = Math.min(imgEl.naturalWidth(), 650);
                Style style = imgEl.getStyle();
                boolean hasWidth = imgEl.hasAttribute("width") || style.getProperty("width") != null;
                if (!hasWidth) {
                    style.setProperty("width", "100%");
                    style.setProperty("minWidth", minWidth + "px");
                    style.setProperty("maxWidth", maxWidth + "px");
                }
                // attach to container
                container.setWidget(image);
                // update widget
                int height = image.getOffsetHeight() + 10;
                onResize.execute(height);
            } else if (DOM.eventGetType(event) == Event.ONERROR) {
                container.setWidget(noImageLabel);
                onResize.execute(50);
            }
        }
    });
    // handle editor resize events
    final Timer renderTimer = new Timer() {

        @Override
        public void run() {
            int height = image.getOffsetHeight() + 30;
            onResize.execute(height);
        }
    };
    // initialize render handler
    renderHandler.set(display.addRenderFinishedHandler(new RenderFinishedEvent.Handler() {

        private int width_;

        @Override
        public void onRenderFinished(RenderFinishedEvent event) {
            int width = display.getBounds().getWidth();
            if (width == width_)
                return;
            width_ = width;
            renderTimer.schedule(100);
        }
    }));
    // initialize doc changed handler
    docChangedHandler.set(display.addDocumentChangedHandler(new DocumentChangedEvent.Handler() {

        private String href_ = href;

        private String attributes_ = StringUtil.notNull(attributes);

        private final Timer refreshImageTimer = new Timer() {

            @Override
            public void run() {
                // if the discovered href isn't an image link, just bail
                if (!ImagePreviewer.isImageHref(href_))
                    return;
                // set new src location (load handler will replace label as needed)
                container.setWidget(new SimplePanel());
                noImageLabel.setText("(No image at path " + href_ + ")");
                image.getElement().setAttribute("src", imgSrcPathFromHref(sentinel, href_));
                // parse and inject attributes
                Map<String, String> parsedAttributes = HTMLAttributesParser.parseAttributes(attributes_);
                final Element imgEl = image.getElement();
                for (Map.Entry<String, String> entry : parsedAttributes.entrySet()) {
                    String key = entry.getKey();
                    String val = entry.getValue();
                    if (StringUtil.isNullOrEmpty(key) || StringUtil.isNullOrEmpty(val))
                        continue;
                    imgEl.setAttribute(key, val);
                }
            }
        };

        private void onDocumentChangedImpl(DocumentChangedEvent event) {
            int row = plw.get().getRow();
            Range range = event.getEvent().getRange();
            if (range.getStart().getRow() <= row && row <= range.getEnd().getRow()) {
                String line = display.getLine(row);
                if (ImagePreviewer.isStandaloneMarkdownLink(line)) {
                    // check to see if the URL text has been updated
                    Token hrefToken = null;
                    JsArray<Token> tokens = display.getTokens(row);
                    for (Token token : JsUtil.asIterable(tokens)) {
                        if (token.hasType("href")) {
                            hrefToken = token;
                            break;
                        }
                    }
                    if (hrefToken == null)
                        return;
                    String attributes = "";
                    int startBraceIdx = line.indexOf("){");
                    int endBraceIdx = line.lastIndexOf("}");
                    if (startBraceIdx != -1 && endBraceIdx != -1 && endBraceIdx > startBraceIdx) {
                        attributes = line.substring(startBraceIdx + 2, endBraceIdx).trim();
                    }
                    // (avoid flickering + re-requests of same URL)
                    if (hrefToken.getValue().equals(href_) && attributes.equals(attributes_))
                        return;
                    // cache href and schedule refresh of image
                    href_ = hrefToken.getValue();
                    attributes_ = attributes;
                    refreshImageTimer.schedule(700);
                } else {
                    onDetach.execute();
                }
            }
        }

        @Override
        public void onDocumentChanged(final DocumentChangedEvent event) {
            // ignore 'removeLines' events as they won't mutate the actual
            // line containing the markdown link
            String action = event.getEvent().getAction();
            if (action.equals("removeLines"))
                return;
            Scheduler.get().scheduleDeferred(new ScheduledCommand() {

                @Override
                public void execute() {
                    onDocumentChangedImpl(event);
                }
            });
        }
    }));
    ChunkOutputHost host = new ChunkOutputHost() {

        @Override
        public void onOutputRemoved(final ChunkOutputWidget widget) {
            onDetach.execute();
        }

        @Override
        public void onOutputHeightChanged(ChunkOutputWidget widget, int height, boolean ensureVisible) {
            onResize.execute(height);
        }
    };
    cow.set(new ChunkOutputWidget(sentinel.getId(), "md-image-preview-" + StringUtil.makeRandomId(8), RmdChunkOptions.create(), ChunkOutputWidget.EXPANDED, // can close
    false, host, ChunkOutputSize.Bare));
    ChunkOutputWidget outputWidget = cow.get();
    outputWidget.setRootWidget(container);
    outputWidget.hideSatellitePopup();
    outputWidget.getElement().getStyle().setMarginTop(4, Unit.PX);
    plw.set(new PinnedLineWidget(LINE_WIDGET_TYPE, display, outputWidget, position.getRow(), null, null));
}
Also used : FadeOutAnimation(org.rstudio.core.client.layout.FadeOutAnimation) ChunkOutputHost(org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkOutputHost) Element(com.google.gwt.dom.client.Element) Label(com.google.gwt.user.client.ui.Label) ImageElementEx(org.rstudio.core.client.dom.ImageElementEx) RenderFinishedEvent(org.rstudio.studio.client.workbench.views.source.editors.text.events.RenderFinishedEvent) Token(org.rstudio.studio.client.workbench.views.source.editors.text.ace.Token) CommandWithArg(org.rstudio.core.client.CommandWithArg) Image(com.google.gwt.user.client.ui.Image) ScheduledCommand(com.google.gwt.core.client.Scheduler.ScheduledCommand) Style(com.google.gwt.dom.client.Style) LineWidget(org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget) DocumentChangedEvent(org.rstudio.studio.client.workbench.views.source.editors.text.events.DocumentChangedEvent) EventListener(com.google.gwt.user.client.EventListener) HandlerRegistration(com.google.gwt.event.shared.HandlerRegistration) SimplePanel(com.google.gwt.user.client.ui.SimplePanel) Range(org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range) Mutable(org.rstudio.core.client.Mutable) Timer(com.google.gwt.user.client.Timer) Command(com.google.gwt.user.client.Command) ScheduledCommand(com.google.gwt.core.client.Scheduler.ScheduledCommand) Event(com.google.gwt.user.client.Event) DocumentChangedEvent(org.rstudio.studio.client.workbench.views.source.editors.text.events.DocumentChangedEvent) RenderFinishedEvent(org.rstudio.studio.client.workbench.views.source.editors.text.events.RenderFinishedEvent) Map(java.util.Map)

Example 8 with LineWidget

use of org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget in project rstudio by rstudio.

the class TextEditingTargetNotebook method removeChunk.

// NOTE: this implements chunk removal locally; prefer firing a
// ChunkChangeEvent if you're removing a chunk so appropriate hooks are
// invoked elsewhere
private void removeChunk(final String chunkId, final String requestId) {
    // ignore if this chunk is currently executing
    if (queue_.isChunkExecuting(chunkId))
        return;
    final ChunkOutputUi output = outputs_.get(chunkId);
    if (output == null) {
        // this case is unexpected; it means that a chunk we don't know about
        // was removed. look for an orphaned line widget matching the chunk ID
        // in case our output map is out of sync.
        LineWidget w = getLineWidget(chunkId);
        if (w != null) {
            docDisplay_.removeLineWidget(w);
            if (w.getElement() != null) {
                w.getElement().getStyle().setDisplay(Display.NONE);
                w.getElement().removeFromParent();
            }
        }
        return;
    }
    // remove any errors in the gutter associated with this chunk
    cleanScopeErrorState(output.getScope());
    ArrayList<Widget> widgets = new ArrayList<Widget>();
    widgets.add(output.getOutputWidget());
    FadeOutAnimation anim = new FadeOutAnimation(widgets, new Command() {

        @Override
        public void execute() {
            // physically remove chunk output
            output.remove();
            outputs_.remove(chunkId);
            // mark doc dirty if interactive (this is not undoable)
            if (StringUtil.isNullOrEmpty(requestId))
                setDirtyState();
        }
    });
    anim.run(400);
}
Also used : FadeOutAnimation(org.rstudio.core.client.layout.FadeOutAnimation) Command(com.google.gwt.user.client.Command) AppCommand(org.rstudio.core.client.command.AppCommand) ArrayList(java.util.ArrayList) PinnedLineWidget(org.rstudio.studio.client.workbench.views.source.editors.text.PinnedLineWidget) Widget(com.google.gwt.user.client.ui.Widget) LineWidget(org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget) ChunkOutputWidget(org.rstudio.studio.client.workbench.views.source.editors.text.ChunkOutputWidget) PinnedLineWidget(org.rstudio.studio.client.workbench.views.source.editors.text.PinnedLineWidget) LineWidget(org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget)

Aggregations

LineWidget (org.rstudio.studio.client.workbench.views.source.editors.text.ace.LineWidget)8 PinnedLineWidget (org.rstudio.studio.client.workbench.views.source.editors.text.PinnedLineWidget)5 ChunkOutputWidget (org.rstudio.studio.client.workbench.views.source.editors.text.ChunkOutputWidget)4 ScheduledCommand (com.google.gwt.core.client.Scheduler.ScheduledCommand)2 Element (com.google.gwt.dom.client.Element)2 Command (com.google.gwt.user.client.Command)2 Map (java.util.Map)2 FadeOutAnimation (org.rstudio.core.client.layout.FadeOutAnimation)2 ChunkOutputHost (org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkOutputHost)2 Style (com.google.gwt.dom.client.Style)1 HandlerRegistration (com.google.gwt.event.shared.HandlerRegistration)1 Event (com.google.gwt.user.client.Event)1 EventListener (com.google.gwt.user.client.EventListener)1 Timer (com.google.gwt.user.client.Timer)1 FlowPanel (com.google.gwt.user.client.ui.FlowPanel)1 Image (com.google.gwt.user.client.ui.Image)1 Label (com.google.gwt.user.client.ui.Label)1 SimplePanel (com.google.gwt.user.client.ui.SimplePanel)1 Widget (com.google.gwt.user.client.ui.Widget)1 ArrayList (java.util.ArrayList)1