use of com.google.gwt.user.client.Timer in project rstudio by rstudio.
the class RCompletionManager method showHelpDeferred.
public void showHelpDeferred(final CompletionRequestContext context, final QualifiedName item, int milliseconds) {
if (helpRequest_ != null && helpRequest_.isRunning())
helpRequest_.cancel();
helpRequest_ = new Timer() {
@Override
public void run() {
if (item.equals(lastSelectedItem_) && popup_.isShowing())
context.showHelp(item);
}
};
helpRequest_.schedule(milliseconds);
}
use of com.google.gwt.user.client.Timer in project rstudio by rstudio.
the class PackagesPane method createPackagesTable.
private void createPackagesTable() {
try {
packagesTableContainer_.clear();
actionCenter_ = null;
packagesTable_ = new DataGrid<PackageInfo>(packagesDataProvider_.getList().size(), dataGridRes_);
} catch (Exception e) {
// in superdevmode, try a few times
if (SuperDevMode.isActive()) {
if (gridRenderRetryCount_ >= 5) {
Debug.log("WARNING: Failed to render packages pane data grid");
}
gridRenderRetryCount_++;
Debug.log("WARNING: Retrying packages data grid render (" + gridRenderRetryCount_ + ")");
Timer t = new Timer() {
@Override
public void run() {
createPackagesTable();
}
};
t.schedule(5);
}
}
if (packagesTable_ != null) {
initPackagesTable();
}
}
use of com.google.gwt.user.client.Timer in project rstudio by rstudio.
the class ChunkOutputFrame method runAfterRender.
public void runAfterRender(final Command command) {
if (command == null)
return;
Timer onRenderedTimer = new Timer() {
private int retryCount_ = 0;
@Override
public void run() {
if (loaded_) {
Element body = getDocument().getBody();
if (body != null && body.getChildCount() > 0) {
command.execute();
} else if (retryCount_ < 50) {
retryCount_++;
schedule(100);
}
}
}
};
onRenderedTimer.schedule(100);
}
use of com.google.gwt.user.client.Timer 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));
}
use of com.google.gwt.user.client.Timer in project rstudio by rstudio.
the class TextEditingTarget method initialize.
public void initialize(final SourceDocument document, FileSystemContext fileContext, FileType type, Provider<String> defaultNameProvider) {
id_ = document.getId();
fileContext_ = fileContext;
fileType_ = (TextFileType) type;
codeExecution_ = new EditingTargetCodeExecution(this, docDisplay_, getId(), this);
extendedType_ = document.getExtendedType();
extendedType_ = rmarkdownHelper_.detectExtendedType(document.getContents(), extendedType_, fileType_);
themeHelper_ = new TextEditingTargetThemeHelper(this, events_);
docUpdateSentinel_ = new DocUpdateSentinel(server_, docDisplay_, document, globalDisplay_.getProgressIndicator("Save File"), dirtyState_, events_);
view_ = new TextEditingTargetWidget(this, docUpdateSentinel_, commands_, prefs_, fileTypeRegistry_, docDisplay_, fileType_, extendedType_, events_, session_);
roxygenHelper_ = new RoxygenHelper(docDisplay_, view_);
// create notebook and forward resize events
chunks_ = new TextEditingTargetChunks(this);
notebook_ = new TextEditingTargetNotebook(this, chunks_, view_, docDisplay_, dirtyState_, docUpdateSentinel_, document, releaseOnDismiss_, dependencyManager_);
view_.addResizeHandler(notebook_);
// ensure that Makefile and Makevars always use tabs
name_.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
if ("Makefile".equals(event.getValue()) || "Makefile.in".equals(event.getValue()) || "Makefile.win".equals(event.getValue()) || "Makevars".equals(event.getValue()) || "Makevars.in".equals(event.getValue()) || "Makevars.win".equals(event.getValue())) {
docDisplay_.setUseSoftTabs(false);
}
}
});
name_.setValue(getNameFromDocument(document, defaultNameProvider), true);
String contents = document.getContents();
docDisplay_.setCode(contents, false);
// Load and apply folds.
final ArrayList<Fold> folds = Fold.decode(document.getFoldSpec());
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
for (Fold fold : folds) docDisplay_.addFold(fold.getRange());
}
});
// Load and apply Vim marks (if they exist).
if (document.getProperties().hasKey("marks")) {
final String marksSpec = document.getProperties().getString("marks");
final JsMap<Position> marks = VimMarks.decode(marksSpec);
// Time out the marks setting just to avoid conflict with other
// mutations of the editor.
new Timer() {
@Override
public void run() {
docDisplay_.setMarks(marks);
}
}.schedule(100);
}
registerPrefs(releaseOnDismiss_, prefs_, docDisplay_, document);
// Initialize sourceOnSave, and keep it in sync
view_.getSourceOnSave().setValue(document.sourceOnSave(), false);
view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>() {
public void onValueChange(ValueChangeEvent<Boolean> event) {
docUpdateSentinel_.setSourceOnSave(event.getValue(), globalDisplay_.getProgressIndicator("Error Saving Setting"));
}
});
if (document.isDirty())
dirtyState_.markDirty(false);
else
dirtyState_.markClean();
docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>() {
public void onValueChange(ValueChangeEvent<Void> event) {
dirtyState_.markDirty(true);
docDisplay_.clearSelectionHistory();
}
});
docDisplay_.addFocusHandler(new FocusHandler() {
public void onFocus(FocusEvent event) {
// let anyone listening know this doc just got focus
events_.fireEvent(new DocFocusedEvent(getPath(), getId()));
if (queuedCollabParams_ != null) {
// of one
if (docDisplay_ != null && !docDisplay_.hasActiveCollabSession()) {
beginQueuedCollabSession();
}
}
// check to see if the file's been saved externally--we do this even
// in a collaborative editing session so we can get delete
// notifications
Scheduler.get().scheduleFixedDelay(new RepeatingCommand() {
public boolean execute() {
if (view_.isAttached())
checkForExternalEdit();
return false;
}
}, 500);
}
});
if (fileType_.isR()) {
docDisplay_.addBreakpointSetHandler(new BreakpointSetEvent.Handler() {
@Override
public void onBreakpointSet(BreakpointSetEvent event) {
if (event.isSet()) {
Breakpoint breakpoint = null;
// don't try to set breakpoints in unsaved code
if (isNewDoc()) {
view_.showWarningBar("Breakpoints cannot be set until " + "the file is saved.");
return;
}
// don't try to set breakpoints if the R version is too old
if (!session_.getSessionInfo().getHaveSrcrefAttribute()) {
view_.showWarningBar("Editor breakpoints require R 2.14 " + "or newer.");
return;
}
Position breakpointPosition = Position.create(event.getLineNumber() - 1, 1);
// if we're not in function scope, or this is a Shiny file,
// set a top-level (aka. Shiny-deferred) breakpoint
ScopeFunction innerFunction = null;
if (extendedType_ == null || !extendedType_.startsWith(SourceDocument.XT_SHINY_PREFIX))
innerFunction = docDisplay_.getFunctionAtPosition(breakpointPosition, false);
if (innerFunction == null || !innerFunction.isFunction() || StringUtil.isNullOrEmpty(innerFunction.getFunctionName())) {
breakpoint = breakpointManager_.setTopLevelBreakpoint(getPath(), event.getLineNumber());
} else // the scope tree will find nested functions, but in R these
// are addressable only as substeps of the parent function.
// keep walking up the scope tree until we've reached the top
// level function.
{
while (innerFunction.getParentScope() != null && innerFunction.getParentScope().isFunction()) {
innerFunction = (ScopeFunction) innerFunction.getParentScope();
}
String functionName = innerFunction.getFunctionName();
breakpoint = breakpointManager_.setBreakpoint(getPath(), functionName, event.getLineNumber(), dirtyState().getValue() == false);
}
docDisplay_.addOrUpdateBreakpoint(breakpoint);
} else {
breakpointManager_.removeBreakpoint(event.getBreakpointId());
}
updateBreakpointWarningBar();
}
});
docDisplay_.addBreakpointMoveHandler(new BreakpointMoveEvent.Handler() {
@Override
public void onBreakpointMove(BreakpointMoveEvent event) {
breakpointManager_.moveBreakpoint(event.getBreakpointId());
}
});
}
// validate required components (e.g. Tex, knitr, C++ etc.)
checkCompilePdfDependencies();
rmarkdownHelper_.verifyPrerequisites(view_, fileType_);
syncFontSize(releaseOnDismiss_, events_, view_, fontSizeManager_);
final String rTypeId = FileTypeRegistry.R.getTypeId();
releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler(new ValueChangeHandler<Boolean>() {
public void onValueChange(ValueChangeEvent<Boolean> evt) {
if (fileType_.getTypeId().equals(rTypeId))
view_.adaptToFileType(fileType_);
}
}));
releaseOnDismiss_.add(events_.addHandler(FileChangeEvent.TYPE, new FileChangeHandler() {
@Override
public void onFileChange(FileChangeEvent event) {
// screen out adds and events that aren't for our path
FileChange fileChange = event.getFileChange();
if (fileChange.getType() == FileChange.ADD)
return;
else if (!fileChange.getFile().getPath().equals(getPath()))
return;
// always check for changes if this is the active editor
if (commandHandlerReg_ != null) {
checkForExternalEdit();
} else // this will show a confirmation dialog
if (event.getFileChange().getType() == FileChange.MODIFIED && dirtyState().getValue() == false) {
checkForExternalEdit();
}
}
}));
spelling_ = new TextEditingTargetSpelling(docDisplay_, docUpdateSentinel_);
// show/hide the debug toolbar when the dirty state changes. (note:
// this doesn't yet handle the case where the user saves the document,
// in which case we should still show some sort of warning.)
dirtyState().addValueChangeHandler(new ValueChangeHandler<Boolean>() {
public void onValueChange(ValueChangeEvent<Boolean> evt) {
updateDebugWarningBar();
}
});
// find all of the debug breakpoints set in this document and replay them
// onto the edit surface
ArrayList<Breakpoint> breakpoints = breakpointManager_.getBreakpointsInFile(getPath());
for (Breakpoint breakpoint : breakpoints) {
docDisplay_.addOrUpdateBreakpoint(breakpoint);
}
if (extendedType_.equals(SourceDocument.XT_RMARKDOWN)) {
// populate the popup menu with a list of available formats
updateRmdFormatList();
setRMarkdownBehaviorEnabled(true);
}
view_.addRmdFormatChangedHandler(new RmdOutputFormatChangedEvent.Handler() {
@Override
public void onRmdOutputFormatChanged(RmdOutputFormatChangedEvent event) {
setRmdFormat(event.getFormat());
}
});
syncPublishPath(document.getPath());
initStatusBar();
}
Aggregations