_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q17000
openLocation
train
function openLocation(location, noFlash) { var editor = EditorManager.getCurrentFullEditor(); var codeMirror = editor._codeMirror; if (typeof location === "number") { location = codeMirror.posFromIndex(location); } codeMirror.setCursor(location); editor.focus(); if (!noFlash) { codeMirror.addLineClass(location.line, "wrap", "flash"); window.setTimeout(function () { codeMirror.removeLineClass(location.line, "wrap", "flash"); }, 1000); } }
javascript
{ "resource": "" }
q17001
open
train
function open(url, location, noFlash) { console.assert(url.substr(0, 7) === "file://", "Cannot open non-file URLs"); var result = new $.Deferred(); url = _urlWithoutQueryString(url); // Extract the path, also strip the third slash when on Windows var path = url.slice(brackets.platform === "win" ? 8 : 7); // URL-decode the path ('%20' => ' ') path = decodeURI(path); var promise = CommandManager.execute(Commands.FILE_OPEN, {fullPath: path}); promise.done(function onDone(doc) { if (location) { openLocation(location, noFlash); } result.resolve(); }); promise.fail(function onErr(err) { console.error(err); result.reject(err); }); return result.promise(); }
javascript
{ "resource": "" }
q17002
_onRemoteGoto
train
function _onRemoteGoto(event, res) { // res = {nodeId, name, value} var location, url = res.value; var matches = /^(.*):([^:]+)$/.exec(url); if (matches) { url = matches[1]; location = matches[2].split(","); if (location.length === 1) { location = parseInt(location[0], 10); } else { location = { line: parseInt(location[0], 10), ch: parseInt(location[1], 10) }; } } open(url, location); }
javascript
{ "resource": "" }
q17003
_removeQuotes
train
function _removeQuotes(src) { if (_isQuote(src[0]) && src[src.length - 1] === src[0]) { var q = src[0]; src = src.substr(1, src.length - 2); src = src.replace("\\" + q, q); } return src; }
javascript
{ "resource": "" }
q17004
_find
train
function _find(src, match, skip, quotes, comments) { if (typeof match === "string") { match = [match, match.length]; } if (skip === undefined) { skip = 0; } var i, activeQuote, isComment = false; for (i = skip; i < src.length; i++) { if (quotes && _isQuote(src[i], src[i - 1], activeQuote)) { // starting quote activeQuote = activeQuote ? undefined : src[i]; } else if (!activeQuote) { if (comments && !isComment && src.substr(i, comments[0].length) === comments[0]) { // opening comment isComment = true; i += comments[0].length - 1; } else if (isComment) { // we are commented if (src.substr(i, comments[1].length) === comments[1]) { isComment = false; i += comments[1].length - 1; } } else if (src.substr(i, match[1]).search(match[0]) === 0) { // match return i; } } } return -1; }
javascript
{ "resource": "" }
q17005
_findEach
train
function _findEach(src, match, quotes, comments, callback) { var from = 0; var to; while (from < src.length) { to = _find(src, match, from, quotes, comments); if (to < 0) { to = src.length; } callback(src.substr(from, to - from)); from = to + 1; } }
javascript
{ "resource": "" }
q17006
_findTag
train
function _findTag(src, skip) { var from, to, inc; from = _find(src, [/<[a-z!\/]/i, 2], skip); if (from < 0) { return null; } if (src.substr(from, 4) === "<!--") { // html comments to = _find(src, "-->", from + 4); inc = 3; } else if (src.substr(from, 7).toLowerCase() === "<script") { // script tag to = _find(src.toLowerCase(), "</script>", from + 7); inc = 9; } else if (src.substr(from, 6).toLowerCase() === "<style") { // style tag to = _find(src.toLowerCase(), "</style>", from + 6); inc = 8; } else { to = _find(src, ">", from + 1, true); inc = 1; } if (to < 0) { return null; } return {from: from, length: to + inc - from}; }
javascript
{ "resource": "" }
q17007
_extractAttributes
train
function _extractAttributes(content) { // remove the node name and the closing bracket and optional slash content = content.replace(/^<\S+\s*/, ""); content = content.replace(/\s*\/?>$/, ""); if (content.length === 0) { return; } // go through the items and identify key value pairs split by = var index, key, value; var attributes = {}; _findEach(content, [/\s/, 1], true, undefined, function each(item) { index = item.search("="); if (index < 0) { return; } // get the key key = item.substr(0, index).trim(); if (key.length === 0) { return; } // get the value value = item.substr(index + 1).trim(); value = _removeQuotes(value); attributes[key] = value; }); return attributes; }
javascript
{ "resource": "" }
q17008
extractPayload
train
function extractPayload(content) { var payload = {}; if (content[0] !== "<") { // text payload.nodeType = 3; payload.nodeValue = content; } else if (content.substr(0, 4) === "<!--") { // comment payload.nodeType = 8; payload.nodeValue = content.substr(4, content.length - 7); } else if (content[1] === "!") { // doctype payload.nodeType = 10; } else { // regular element payload.nodeType = 1; payload.nodeName = /^<([^>\s]+)/.exec(content)[1].toUpperCase(); payload.attributes = _extractAttributes(content); // closing node (/ at the beginning) if (payload.nodeName[0] === "/") { payload.nodeName = payload.nodeName.substr(1); payload.closing = true; } // closed node (/ at the end) if (content[content.length - 2] === "/") { payload.closed = true; } // Special handling for script/style tag since we've already collected // everything up to the end tag. if (payload.nodeName === "SCRIPT" || payload.nodeName === "STYLE") { payload.closed = true; } } return payload; }
javascript
{ "resource": "" }
q17009
eachNode
train
function eachNode(src, callback) { var index = 0; var text, range, length, payload; while (index < src.length) { // find the next tag range = _findTag(src, index); if (!range) { range = { from: src.length, length: 0 }; } // add the text before the tag length = range.from - index; if (length > 0) { text = src.substr(index, length); if (/\S/.test(text)) { payload = extractPayload(text); payload.sourceOffset = index; payload.sourceLength = length; callback(payload); } } // add the tag if (range.length > 0) { payload = extractPayload(src.substr(range.from, range.length)); payload.sourceOffset = range.from; payload.sourceLength = range.length; callback(payload); } // advance index = range.from + range.length; } }
javascript
{ "resource": "" }
q17010
Document
train
function Document(file, initialTimestamp, rawText) { this.file = file; this.editable = !file.readOnly; this._updateLanguage(); this.refreshText(rawText, initialTimestamp, true); // List of full editors which are initialized as master editors for this doc. this._associatedFullEditors = []; }
javascript
{ "resource": "" }
q17011
call
train
function call(method, varargs) { var argsArray = [_objectId, "_LD." + method]; if (arguments.length > 1) { argsArray = argsArray.concat(Array.prototype.slice.call(arguments, 1)); } return _call.apply(null, argsArray); }
javascript
{ "resource": "" }
q17012
InlineColorEditor
train
function InlineColorEditor(color, marker) { this._color = color; this._marker = marker; this._isOwnChange = false; this._isHostChange = false; this._origin = "+InlineColorEditor_" + (lastOriginId++); this._handleColorChange = this._handleColorChange.bind(this); this._handleHostDocumentChange = this._handleHostDocumentChange.bind(this); InlineWidget.call(this); }
javascript
{ "resource": "" }
q17013
_colorSort
train
function _colorSort(a, b) { if (a.count === b.count) { return 0; } if (a.count > b.count) { return -1; } if (a.count < b.count) { return 1; } }
javascript
{ "resource": "" }
q17014
isValidDrop
train
function isValidDrop(items) { var i, len = items.length; for (i = 0; i < len; i++) { if (items[i].kind === "file") { var entry = items[i].webkitGetAsEntry(); if (entry.isFile) { // If any files are being dropped, this is a valid drop return true; } else if (len === 1) { // If exactly one folder is being dropped, this is a valid drop return true; } } } // No valid entries found return false; }
javascript
{ "resource": "" }
q17015
stopURIListPropagation
train
function stopURIListPropagation(files, event) { var types = event.dataTransfer.types; if ((!files || !files.length) && types) { // We only want to check if a string of text was dragged into the editor types.forEach(function (value) { //Dragging text externally (dragging text from another file): types has "text/plain" and "text/html" //Dragging text internally (dragging text to another line): types has just "text/plain" //Dragging a file: types has "Files" //Dragging a url: types has "text/plain" and "text/uri-list" <-what we are interested in if (value === "text/uri-list") { event.stopPropagation(); event.preventDefault(); return; } }); } }
javascript
{ "resource": "" }
q17016
openDroppedFiles
train
function openDroppedFiles(paths) { var errorFiles = [], ERR_MULTIPLE_ITEMS_WITH_DIR = {}; return Async.doInParallel(paths, function (path, idx) { var result = new $.Deferred(); // Only open files. FileSystem.resolve(path, function (err, item) { if (!err && item.isFile) { // If the file is already open, and this isn't the last // file in the list, return. If this *is* the last file, // always open it so it gets selected. if (idx < paths.length - 1) { if (MainViewManager.findInWorkingSet(MainViewManager.ALL_PANES, path) !== -1) { result.resolve(); return; } } CommandManager.execute(Commands.CMD_ADD_TO_WORKINGSET_AND_OPEN, {fullPath: path, silent: true}) .done(function () { result.resolve(); }) .fail(function (openErr) { errorFiles.push({path: path, error: openErr}); result.reject(); }); } else if (!err && item.isDirectory && paths.length === 1) { // One folder was dropped, open it. ProjectManager.openProject(path) .done(function () { result.resolve(); }) .fail(function () { // User was already notified of the error. result.reject(); }); } else { errorFiles.push({path: path, error: err || ERR_MULTIPLE_ITEMS_WITH_DIR}); result.reject(); } }); return result.promise(); }, false) .fail(function () { function errorToString(err) { if (err === ERR_MULTIPLE_ITEMS_WITH_DIR) { return Strings.ERROR_MIXED_DRAGDROP; } else { return FileUtils.getFileErrorString(err); } } if (errorFiles.length > 0) { var message = Strings.ERROR_OPENING_FILES; message += "<ul class='dialog-list'>"; errorFiles.forEach(function (info) { message += "<li><span class='dialog-filename'>" + StringUtils.breakableUrl(ProjectManager.makeProjectRelativeIfPossible(info.path)) + "</span> - " + errorToString(info.error) + "</li>"; }); message += "</ul>"; Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_ERROR, Strings.ERROR_OPENING_FILE_TITLE, message ); } }); }
javascript
{ "resource": "" }
q17017
_calcScaling
train
function _calcScaling() { var $sb = _getScrollbar(editor); trackHt = $sb[0].offsetHeight; if (trackHt > 0) { trackOffset = getScrollbarTrackOffset(); trackHt -= trackOffset * 2; } else { // No scrollbar: use the height of the entire code content var codeContainer = $(editor.getRootElement()).find("> .CodeMirror-scroll > .CodeMirror-sizer > div > .CodeMirror-lines > div")[0]; trackHt = codeContainer.offsetHeight; trackOffset = codeContainer.offsetTop; } }
javascript
{ "resource": "" }
q17018
_renderMarks
train
function _renderMarks(posArray) { var html = "", cm = editor._codeMirror, editorHt = cm.getScrollerElement().scrollHeight; // We've pretty much taken these vars and the getY function from CodeMirror's annotatescrollbar addon // https://github.com/codemirror/CodeMirror/blob/master/addon/scroll/annotatescrollbar.js var wrapping = cm.getOption("lineWrapping"), singleLineH = wrapping && cm.defaultTextHeight() * 1.5, curLine = null, curLineObj = null; function getY(cm, pos) { if (curLine !== pos.line) { curLine = pos.line; curLineObj = cm.getLineHandle(curLine); } if (wrapping && curLineObj.height > singleLineH) { return cm.charCoords(pos, "local").top; } return cm.heightAtLine(curLineObj, "local"); } posArray.forEach(function (pos) { var cursorTop = getY(cm, pos), top = Math.round(cursorTop / editorHt * trackHt) + trackOffset; top--; // subtract ~1/2 the ht of a tickmark to center it on ideal pos html += "<div class='tickmark' style='top:" + top + "px'></div>"; }); $(".tickmark-track", editor.getRootElement()).append($(html)); }
javascript
{ "resource": "" }
q17019
setVisible
train
function setVisible(curEditor, visible) { // short-circuit no-ops if ((visible && curEditor === editor) || (!visible && !editor)) { return; } if (visible) { console.assert(!editor); editor = curEditor; // Don't support inline editors yet - search inside them is pretty screwy anyway (#2110) if (editor.isTextSubset()) { return; } var $sb = _getScrollbar(editor), $overlay = $("<div class='tickmark-track'></div>"); $sb.parent().append($overlay); _calcScaling(); // Update tickmarks during editor resize (whenever resizing has paused/stopped for > 1/3 sec) WorkspaceManager.on("workspaceUpdateLayout.ScrollTrackMarkers", _.debounce(function () { if (marks.length) { _calcScaling(); $(".tickmark-track", editor.getRootElement()).empty(); _renderMarks(marks); } }, 300)); } else { console.assert(editor === curEditor); $(".tickmark-track", curEditor.getRootElement()).remove(); editor = null; marks = []; WorkspaceManager.off("workspaceUpdateLayout.ScrollTrackMarkers"); } }
javascript
{ "resource": "" }
q17020
addTickmarks
train
function addTickmarks(curEditor, posArray) { console.assert(editor === curEditor); marks = marks.concat(posArray); _renderMarks(posArray); }
javascript
{ "resource": "" }
q17021
maybeIdentifier
train
function maybeIdentifier(key) { var result = false, i; for (i = 0; i < key.length; i++) { result = Acorn.isIdentifierChar(key.charCodeAt(i)); if (!result) { break; } } return result; }
javascript
{ "resource": "" }
q17022
_closeSubtree
train
function _closeSubtree(directory) { directory = directory.delete("open"); var children = directory.get("children"); if (children) { children.keySeq().forEach(function (name) { var subdir = children.get(name); if (!isFile(subdir)) { subdir = _closeSubtree(subdir); children = children.set(name, subdir); } }); } directory = directory.set("children", children); return directory; }
javascript
{ "resource": "" }
q17023
getRefs
train
function getRefs(fileInfo, offset) { ScopeManager.postMessage({ type: MessageIds.TERN_REFS, fileInfo: fileInfo, offset: offset }); return ScopeManager.addPendingRequest(fileInfo.name, offset, MessageIds.TERN_REFS); }
javascript
{ "resource": "" }
q17024
requestFindRefs
train
function requestFindRefs(session, document, offset) { if (!document || !session) { return; } var path = document.file.fullPath, fileInfo = { type: MessageIds.TERN_FILE_INFO_TYPE_FULL, name: path, offsetLines: 0, text: ScopeManager.filterText(session.getJavascriptText()) }; var ternPromise = getRefs(fileInfo, offset); return {promise: ternPromise}; }
javascript
{ "resource": "" }
q17025
handleFindRefs
train
function handleFindRefs (refsResp) { if (!refsResp || !refsResp.references || !refsResp.references.refs) { return; } var inlineWidget = EditorManager.getFocusedInlineWidget(), editor = EditorManager.getActiveEditor(), refs = refsResp.references.refs, type = refsResp.references.type; //In case of inline widget if some references are outside widget's text range then don't allow for rename if (inlineWidget) { var isInTextRange = !refs.find(function(item) { return (item.start.line < inlineWidget._startLine || item.end.line > inlineWidget._endLine); }); if (!isInTextRange) { editor.displayErrorMessageAtCursor(Strings.ERROR_RENAME_QUICKEDIT); return; } } var currentPosition = editor.posFromIndex(refsResp.offset), refsArray = refs; if (type !== "local") { refsArray = refs.filter(function (element) { return isInSameFile(element, refsResp); }); } // Finding the Primary Reference in Array var primaryRef = refsArray.find(function (element) { return ((element.start.line === currentPosition.line || element.end.line === currentPosition.line) && currentPosition.ch <= element.end.ch && currentPosition.ch >= element.start.ch); }); // Setting the primary flag of Primary Refence to true primaryRef.primary = true; editor.setSelections(refsArray); }
javascript
{ "resource": "" }
q17026
requestFindReferences
train
function requestFindReferences(session, offset) { var response = requestFindRefs(session, session.editor.document, offset); if (response && response.hasOwnProperty("promise")) { response.promise.done(handleFindRefs).fail(function () { result.reject(); }); } }
javascript
{ "resource": "" }
q17027
_classForDocument
train
function _classForDocument(doc) { switch (doc.getLanguage().getId()) { case "less": case "scss": return CSSPreprocessorDocument; case "css": return CSSDocument; case "javascript": return exports.config.experimental ? JSDocument : null; } if (LiveDevelopmentUtils.isHtmlFileExt(doc.file.fullPath)) { return HTMLDocument; } return null; }
javascript
{ "resource": "" }
q17028
enableAgent
train
function enableAgent(name) { if (agents.hasOwnProperty(name) && !_enabledAgentNames.hasOwnProperty(name)) { _enabledAgentNames[name] = true; } }
javascript
{ "resource": "" }
q17029
_onError
train
function _onError(event, error, msgData) { var message; // Sometimes error.message is undefined if (!error.message) { console.warn("Expected a non-empty string in error.message, got this instead:", error.message); message = JSON.stringify(error); } else { message = error.message; } // Remove "Uncaught" from the beginning to avoid the inspector popping up if (message && message.substr(0, 8) === "Uncaught") { message = message.substr(9); } // Additional information, like exactly which parameter could not be processed. var data = error.data; if (Array.isArray(data)) { message += "\n" + data.join("\n"); } // Show the message, but include the error object for further information (e.g. error code) console.error(message, error, msgData); }
javascript
{ "resource": "" }
q17030
loadAgents
train
function loadAgents() { // If we're already loading agents return same promise if (_loadAgentsPromise) { return _loadAgentsPromise; } var result = new $.Deferred(), allAgentsPromise; _loadAgentsPromise = result.promise(); _setStatus(STATUS_LOADING_AGENTS); // load agents in parallel allAgentsPromise = Async.doInParallel( getEnabledAgents(), function (name) { return _invokeAgentMethod(name, "load").done(function () { _loadedAgentNames.push(name); }); }, true ); // wrap agent loading with a timeout allAgentsPromise = Async.withTimeout(allAgentsPromise, 10000); allAgentsPromise.done(function () { var doc = (_liveDocument) ? _liveDocument.doc : null; if (doc) { var status = STATUS_ACTIVE; if (_docIsOutOfSync(doc)) { status = STATUS_OUT_OF_SYNC; } _setStatus(status); result.resolve(); } else { result.reject(); } }); allAgentsPromise.fail(result.reject); _loadAgentsPromise .fail(function () { // show error loading live dev dialog _setStatus(STATUS_ERROR); Dialogs.showModalDialog( Dialogs.DIALOG_ID_ERROR, Strings.LIVE_DEVELOPMENT_ERROR_TITLE, _makeTroubleshootingMessage(Strings.LIVE_DEV_LOADING_ERROR_MESSAGE) ); }) .always(function () { _loadAgentsPromise = null; }); return _loadAgentsPromise; }
javascript
{ "resource": "" }
q17031
onActiveEditorChange
train
function onActiveEditorChange(event, current, previous) { if (previous && previous.document && CSSUtils.isCSSPreprocessorFile(previous.document.file.fullPath)) { var prevDocUrl = _server && _server.pathToUrl(previous.document.file.fullPath); if (_relatedDocuments && _relatedDocuments[prevDocUrl]) { _closeRelatedDocument(_relatedDocuments[prevDocUrl]); } } if (current && current.document && CSSUtils.isCSSPreprocessorFile(current.document.file.fullPath)) { var docUrl = _server && _server.pathToUrl(current.document.file.fullPath); _styleSheetAdded(null, docUrl); } }
javascript
{ "resource": "" }
q17032
reconnect
train
function reconnect() { if (_loadAgentsPromise) { // Agents are already loading, so don't unload return _loadAgentsPromise; } unloadAgents(); // Clear any existing related documents before we reload the agents. // We need to recreate them for the reloaded document due to some // desirable side-effects (see #7606). Eventually, we should simplify // the way we get that behavior. _.forOwn(_relatedDocuments, function (relatedDoc) { _closeRelatedDocument(relatedDoc); }); return loadAgents(); }
javascript
{ "resource": "" }
q17033
_onConnect
train
function _onConnect(event) { // When the browser navigates away from the primary live document Inspector.Page.on("frameNavigated.livedev", _onFrameNavigated); // When the Inspector WebSocket disconnects unexpectedely Inspector.on("disconnect.livedev", _onDisconnect); _waitForInterstitialPageLoad() .fail(function () { close(); Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_ERROR, Strings.LIVE_DEVELOPMENT_ERROR_TITLE, _makeTroubleshootingMessage(Strings.LIVE_DEV_LOADING_ERROR_MESSAGE) ); }) .done(_onInterstitialPageLoad); }
javascript
{ "resource": "" }
q17034
_doLaunchAfterServerReady
train
function _doLaunchAfterServerReady(initialDoc) { // update status _setStatus(STATUS_CONNECTING); _createLiveDocumentForFrame(initialDoc); // start listening for requests _server.start(); // Install a one-time event handler when connected to the launcher page Inspector.one("connect", _onConnect); // open browser to the interstitial page to prepare for loading agents _openInterstitialPage(); // Once all agents loaded (see _onInterstitialPageLoad()), begin Live Highlighting for preprocessor documents _openDeferred.done(function () { // Setup activeEditorChange event listener so that we can track cursor positions in // CSS preprocessor files and perform live preview highlighting on all elements with // the current selector in the preprocessor file. EditorManager.on("activeEditorChange", onActiveEditorChange); // Explicitly trigger onActiveEditorChange so that live preview highlighting // can be set up for the preprocessor files. onActiveEditorChange(null, EditorManager.getActiveEditor(), null); }); }
javascript
{ "resource": "" }
q17035
open
train
function open(restart) { // If close() is still pending, wait for close to finish before opening if (_isPromisePending(_closeDeferred)) { return _closeDeferred.then(function () { return open(restart); }); } if (!restart) { // Return existing promise if it is still pending if (_isPromisePending(_openDeferred)) { return _openDeferred; } else { _openDeferred = new $.Deferred(); _openDeferred.always(function () { _openDeferred = null; }); } } // Send analytics data when Live Preview is opened HealthLogger.sendAnalyticsData( "livePreviewOpen", "usage", "livePreview", "open" ); // Register user defined server provider and keep handlers for further clean-up _regServers.push(LiveDevServerManager.registerServer({ create: _createUserServer }, 99)); _regServers.push(LiveDevServerManager.registerServer({ create: _createFileServer }, 0)); // TODO: need to run _onFileChanged() after load if doc != currentDocument here? Maybe not, since activeEditorChange // doesn't trigger it, while inline editors can still cause edits in doc other than currentDoc... _getInitialDocFromCurrent().done(function (doc) { var prepareServerPromise = (doc && _prepareServer(doc)) || new $.Deferred().reject(), otherDocumentsInWorkingFiles; if (doc && !doc._masterEditor) { otherDocumentsInWorkingFiles = MainViewManager.getWorkingSet(MainViewManager.ALL_PANES).length; MainViewManager.addToWorkingSet(MainViewManager.ACTIVE_PANE, doc.file); if (!otherDocumentsInWorkingFiles) { MainViewManager._edit(MainViewManager.ACTIVE_PANE, doc); } } // wait for server (StaticServer, Base URL or file:) prepareServerPromise .done(function () { var reverseInspectPref = PreferencesManager.get("livedev.enableReverseInspect"), wsPort = PreferencesManager.get("livedev.wsPort"); if (wsPort && reverseInspectPref) { WebSocketTransport.createWebSocketServer(wsPort); } _doLaunchAfterServerReady(doc); }) .fail(function () { _showWrongDocError(); }); }); return _openDeferred.promise(); }
javascript
{ "resource": "" }
q17036
_onDocumentSaved
train
function _onDocumentSaved(event, doc) { if (!Inspector.connected() || !_server) { return; } var absolutePath = doc.file.fullPath, liveDocument = absolutePath && _server.get(absolutePath), liveEditingEnabled = liveDocument && liveDocument.isLiveEditingEnabled && liveDocument.isLiveEditingEnabled(); // Skip reload if the saved document has live editing enabled if (liveEditingEnabled) { return; } var documentUrl = _server.pathToUrl(absolutePath), wasRequested = agents.network && agents.network.wasURLRequested(documentUrl); if (wasRequested) { reload(); } }
javascript
{ "resource": "" }
q17037
_onDirtyFlagChange
train
function _onDirtyFlagChange(event, doc) { if (doc && Inspector.connected() && _server && agents.network && agents.network.wasURLRequested(_server.pathToUrl(doc.file.fullPath))) { // Set status to out of sync if dirty. Otherwise, set it to active status. _setStatus(_docIsOutOfSync(doc) ? STATUS_OUT_OF_SYNC : STATUS_ACTIVE); } }
javascript
{ "resource": "" }
q17038
init
train
function init(theConfig) { exports.config = theConfig; Inspector.on("error", _onError); Inspector.Inspector.on("detached", _onDetached); // Only listen for styleSheetAdded // We may get interim added/removed events when pushing incremental updates CSSAgent.on("styleSheetAdded.livedev", _styleSheetAdded); MainViewManager .on("currentFileChange", _onFileChanged); DocumentManager .on("documentSaved", _onDocumentSaved) .on("dirtyFlagChange", _onDirtyFlagChange); ProjectManager .on("beforeProjectClose beforeAppClose", close); // Initialize exports.status _setStatus(STATUS_INACTIVE); }
javascript
{ "resource": "" }
q17039
addCommand
train
function addCommand() { CommandManager.register(Strings.CMD_HEALTH_DATA_STATISTICS, healthDataCmdId, handleHealthDataStatistics); menu.addMenuItem(healthDataCmdId, "", Menus.AFTER, Commands.HELP_SHOW_EXT_FOLDER); menu.addMenuDivider(Menus.AFTER, Commands.HELP_SHOW_EXT_FOLDER); }
javascript
{ "resource": "" }
q17040
getCurrentFullEditor
train
function getCurrentFullEditor() { var currentPath = MainViewManager.getCurrentlyViewedPath(MainViewManager.ACTIVE_PANE), doc = currentPath && DocumentManager.getOpenDocumentForPath(currentPath); return doc && doc._masterEditor; }
javascript
{ "resource": "" }
q17041
_restoreEditorViewState
train
function _restoreEditorViewState(editor) { // We want to ignore the current state of the editor, so don't call __getViewState() var viewState = ViewStateManager.getViewState(editor.document.file); if (viewState) { editor.restoreViewState(viewState); } }
javascript
{ "resource": "" }
q17042
_notifyActiveEditorChanged
train
function _notifyActiveEditorChanged(current) { // Skip if the Editor that gained focus was already the most recently focused editor. // This may happen e.g. if the window loses then regains focus. if (_lastFocusedEditor === current) { return; } var previous = _lastFocusedEditor; _lastFocusedEditor = current; exports.trigger("activeEditorChange", current, previous); }
javascript
{ "resource": "" }
q17043
_createEditorForDocument
train
function _createEditorForDocument(doc, makeMasterEditor, container, range, editorOptions) { var editor = new Editor(doc, makeMasterEditor, container, range, editorOptions); editor.on("focus", function () { _notifyActiveEditorChanged(editor); }); editor.on("beforeDestroy", function () { if (editor.$el.is(":visible")) { _saveEditorViewState(editor); } }); return editor; }
javascript
{ "resource": "" }
q17044
_toggleInlineWidget
train
function _toggleInlineWidget(providers, errorMsg) { var result = new $.Deferred(); var currentEditor = getCurrentFullEditor(); if (currentEditor) { var inlineWidget = currentEditor.getFocusedInlineWidget(); if (inlineWidget) { // an inline widget's editor has focus, so close it PerfUtils.markStart(PerfUtils.INLINE_WIDGET_CLOSE); inlineWidget.close().done(function () { PerfUtils.addMeasurement(PerfUtils.INLINE_WIDGET_CLOSE); // return a resolved promise to CommandManager result.resolve(false); }); } else { // main editor has focus, so create an inline editor _openInlineWidget(currentEditor, providers, errorMsg).done(function () { result.resolve(true); }).fail(function () { result.reject(); }); } } else { // Can not open an inline editor without a host editor result.reject(); } return result.promise(); }
javascript
{ "resource": "" }
q17045
registerInlineEditProvider
train
function registerInlineEditProvider(provider, priority) { if (priority === undefined) { priority = 0; } _insertProviderSorted(_inlineEditProviders, provider, priority); }
javascript
{ "resource": "" }
q17046
registerInlineDocsProvider
train
function registerInlineDocsProvider(provider, priority) { if (priority === undefined) { priority = 0; } _insertProviderSorted(_inlineDocsProviders, provider, priority); }
javascript
{ "resource": "" }
q17047
openDocument
train
function openDocument(doc, pane, editorOptions) { var perfTimerName = PerfUtils.markStart("EditorManager.openDocument():\t" + (!doc || doc.file.fullPath)); if (doc && pane) { _showEditor(doc, pane, editorOptions); } PerfUtils.addMeasurement(perfTimerName); }
javascript
{ "resource": "" }
q17048
_handleRemoveFromPaneView
train
function _handleRemoveFromPaneView(e, removedFiles) { var handleFileRemoved = function (file) { var doc = DocumentManager.getOpenDocumentForPath(file.fullPath); if (doc) { MainViewManager._destroyEditorIfNotNeeded(doc); } }; // when files are removed from a pane then // we should destroy any unnecssary views if ($.isArray(removedFiles)) { removedFiles.forEach(function (removedFile) { handleFileRemoved(removedFile); }); } else { handleFileRemoved(removedFiles); } }
javascript
{ "resource": "" }
q17049
_setContextMenuItemsVisible
train
function _setContextMenuItemsVisible(enabled, items) { items.forEach(function (item) { CommandManager.get(item).setEnabled(enabled); }); }
javascript
{ "resource": "" }
q17050
_setMenuItemsVisible
train
function _setMenuItemsVisible() { var file = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE); if (file) { file.exists(function (err, isPresent) { if (err) { return err; } _setContextMenuItemsVisible(isPresent, [Commands.FILE_RENAME, Commands.NAVIGATE_SHOW_IN_FILE_TREE, Commands.NAVIGATE_SHOW_IN_OS]); }); } }
javascript
{ "resource": "" }
q17051
normalizeStats
train
function normalizeStats(nodeFsStats) { // current shell's stat method floors the mtime to the nearest thousand // which causes problems when comparing timestamps // so we have to round mtime to the nearest thousand too var mtime = Math.floor(nodeFsStats.mtime.getTime() / 1000) * 1000; // from shell: If "filename" is a symlink, // realPath should be the actual path to the linked object // not implemented in shell yet return { isFile: nodeFsStats.isFile(), isDirectory: nodeFsStats.isDirectory(), mtime: mtime, size: nodeFsStats.size, realPath: null, hash: mtime }; }
javascript
{ "resource": "" }
q17052
_unwatchPath
train
function _unwatchPath(path) { var watcher = _watcherMap[path]; if (watcher) { try { watcher.close(); } catch (err) { console.warn("Failed to unwatch file " + path + ": " + (err && err.message)); } finally { delete _watcherMap[path]; } } }
javascript
{ "resource": "" }
q17053
unwatchPath
train
function unwatchPath(path) { Object.keys(_watcherMap).forEach(function (keyPath) { if (keyPath.indexOf(path) === 0) { _unwatchPath(keyPath); } }); }
javascript
{ "resource": "" }
q17054
watchPath
train
function watchPath(path, ignored) { if (_watcherMap.hasOwnProperty(path)) { return; } return _watcherImpl.watchPath(path, ignored, _watcherMap, _domainManager); }
javascript
{ "resource": "" }
q17055
_shortTitleForDocument
train
function _shortTitleForDocument(doc) { var fullPath = doc.file.fullPath; // If the document is untitled then return the filename, ("Untitled-n.ext"); // otherwise show the project-relative path if the file is inside the // current project or the full absolute path if it's not in the project. if (doc.isUntitled()) { return fullPath.substring(fullPath.lastIndexOf("/") + 1); } else { return ProjectManager.makeProjectRelativeIfPossible(fullPath); } }
javascript
{ "resource": "" }
q17056
handleCurrentFileChange
train
function handleCurrentFileChange() { var newFile = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE); if (newFile) { var newDocument = DocumentManager.getOpenDocumentForPath(newFile.fullPath); if (newDocument) { _currentTitlePath = _shortTitleForDocument(newDocument); } else { _currentTitlePath = ProjectManager.makeProjectRelativeIfPossible(newFile.fullPath); } } else { _currentTitlePath = null; } // Update title text & "dirty dot" display _updateTitle(); }
javascript
{ "resource": "" }
q17057
handleDirtyChange
train
function handleDirtyChange(event, changedDoc) { var currentDoc = DocumentManager.getCurrentDocument(); if (currentDoc && changedDoc.file.fullPath === currentDoc.file.fullPath) { _updateTitle(); } }
javascript
{ "resource": "" }
q17058
showFileOpenError
train
function showFileOpenError(name, path) { return Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_ERROR, Strings.ERROR_OPENING_FILE_TITLE, StringUtils.format( Strings.ERROR_OPENING_FILE, StringUtils.breakableUrl(path), FileUtils.getFileErrorString(name) ) ); }
javascript
{ "resource": "" }
q17059
handleDocumentOpen
train
function handleDocumentOpen(commandData) { var result = new $.Deferred(); handleFileOpen(commandData) .done(function (file) { // if we succeeded with an open file // then we need to resolve that to a document. // getOpenDocumentForPath will return null if there isn't a // supporting document for that file (e.g. an image) var doc = DocumentManager.getOpenDocumentForPath(file.fullPath); result.resolve(doc); }) .fail(function (err) { result.reject(err); }); return result.promise(); }
javascript
{ "resource": "" }
q17060
handleFileAddToWorkingSetAndOpen
train
function handleFileAddToWorkingSetAndOpen(commandData) { return handleFileOpen(commandData).done(function (file) { var paneId = (commandData && commandData.paneId) || MainViewManager.ACTIVE_PANE; MainViewManager.addToWorkingSet(paneId, file, commandData.index, commandData.forceRedraw); HealthLogger.fileOpened(file.fullPath, true); }); }
javascript
{ "resource": "" }
q17061
_handleNewItemInProject
train
function _handleNewItemInProject(isFolder) { if (fileNewInProgress) { ProjectManager.forceFinishRename(); return; } fileNewInProgress = true; // Determine the directory to put the new file // If a file is currently selected in the tree, put it next to it. // If a directory is currently selected in the tree, put it in it. // If an Untitled document is selected or nothing is selected in the tree, put it at the root of the project. var baseDirEntry, selected = ProjectManager.getFileTreeContext(); if ((!selected) || (selected instanceof InMemoryFile)) { selected = ProjectManager.getProjectRoot(); } if (selected.isFile) { baseDirEntry = FileSystem.getDirectoryForPath(selected.parentPath); } baseDirEntry = baseDirEntry || selected; // Create the new node. The createNewItem function does all the heavy work // of validating file name, creating the new file and selecting. function createWithSuggestedName(suggestedName) { return ProjectManager.createNewItem(baseDirEntry, suggestedName, false, isFolder) .always(function () { fileNewInProgress = false; }); } return _getUntitledFileSuggestion(baseDirEntry, Strings.UNTITLED, isFolder) .then(createWithSuggestedName, createWithSuggestedName.bind(undefined, Strings.UNTITLED)); }
javascript
{ "resource": "" }
q17062
createWithSuggestedName
train
function createWithSuggestedName(suggestedName) { return ProjectManager.createNewItem(baseDirEntry, suggestedName, false, isFolder) .always(function () { fileNewInProgress = false; }); }
javascript
{ "resource": "" }
q17063
doSave
train
function doSave(docToSave, force) { var result = new $.Deferred(), file = docToSave.file; function handleError(error) { _showSaveFileError(error, file.fullPath) .done(function () { result.reject(error); }); } function handleContentsModified() { Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_ERROR, Strings.EXT_MODIFIED_TITLE, StringUtils.format( Strings.EXT_MODIFIED_WARNING, StringUtils.breakableUrl(docToSave.file.fullPath) ), [ { className : Dialogs.DIALOG_BTN_CLASS_LEFT, id : Dialogs.DIALOG_BTN_SAVE_AS, text : Strings.SAVE_AS }, { className : Dialogs.DIALOG_BTN_CLASS_NORMAL, id : Dialogs.DIALOG_BTN_CANCEL, text : Strings.CANCEL }, { className : Dialogs.DIALOG_BTN_CLASS_PRIMARY, id : Dialogs.DIALOG_BTN_OK, text : Strings.SAVE_AND_OVERWRITE } ] ) .done(function (id) { if (id === Dialogs.DIALOG_BTN_CANCEL) { result.reject(); } else if (id === Dialogs.DIALOG_BTN_OK) { // Re-do the save, ignoring any CONTENTS_MODIFIED errors doSave(docToSave, true).then(result.resolve, result.reject); } else if (id === Dialogs.DIALOG_BTN_SAVE_AS) { // Let the user choose a different path at which to write the file handleFileSaveAs({doc: docToSave}).then(result.resolve, result.reject); } }); } function trySave() { // We don't want normalized line endings, so it's important to pass true to getText() FileUtils.writeText(file, docToSave.getText(true), force) .done(function () { docToSave.notifySaved(); result.resolve(file); HealthLogger.fileSaved(docToSave); }) .fail(function (err) { if (err === FileSystemError.CONTENTS_MODIFIED) { handleContentsModified(); } else { handleError(err); } }); } if (docToSave.isDirty) { if (docToSave.keepChangesTime) { // The user has decided to keep conflicting changes in the editor. Check to make sure // the file hasn't changed since they last decided to do that. docToSave.file.stat(function (err, stat) { // If the file has been deleted on disk, the stat will return an error, but that's fine since // that means there's no file to overwrite anyway, so the save will succeed without us having // to set force = true. if (!err && docToSave.keepChangesTime === stat.mtime.getTime()) { // OK, it's safe to overwrite the file even though we never reloaded the latest version, // since the user already said s/he wanted to ignore the disk version. force = true; } trySave(); }); } else { trySave(); } } else { result.resolve(file); } result.always(function () { MainViewManager.focusActivePane(); }); return result.promise(); }
javascript
{ "resource": "" }
q17064
_doRevert
train
function _doRevert(doc, suppressError) { var result = new $.Deferred(); FileUtils.readAsText(doc.file) .done(function (text, readTimestamp) { doc.refreshText(text, readTimestamp); result.resolve(); }) .fail(function (error) { if (suppressError) { result.resolve(); } else { showFileOpenError(error, doc.file.fullPath) .done(function () { result.reject(error); }); } }); return result.promise(); }
javascript
{ "resource": "" }
q17065
_configureEditorAndResolve
train
function _configureEditorAndResolve() { var editor = EditorManager.getActiveEditor(); if (editor) { if (settings) { editor.setSelections(settings.selections); editor.setScrollPos(settings.scrollPos.x, settings.scrollPos.y); } } result.resolve(newFile); }
javascript
{ "resource": "" }
q17066
openNewFile
train
function openNewFile() { var fileOpenPromise; if (FileViewController.getFileSelectionFocus() === FileViewController.PROJECT_MANAGER) { // If selection is in the tree, leave workingset unchanged - even if orig file is in the list fileOpenPromise = FileViewController .openAndSelectDocument(path, FileViewController.PROJECT_MANAGER); } else { // If selection is in workingset, replace orig item in place with the new file var info = MainViewManager.findInAllWorkingSets(doc.file.fullPath).shift(); // Remove old file from workingset; no redraw yet since there's a pause before the new file is opened MainViewManager._removeView(info.paneId, doc.file, true); // Add new file to workingset, and ensure we now redraw (even if index hasn't changed) fileOpenPromise = handleFileAddToWorkingSetAndOpen({fullPath: path, paneId: info.paneId, index: info.index, forceRedraw: true}); } // always configure editor after file is opened fileOpenPromise.always(function () { _configureEditorAndResolve(); }); }
javascript
{ "resource": "" }
q17067
handleFileSave
train
function handleFileSave(commandData) { var activeEditor = EditorManager.getActiveEditor(), activeDoc = activeEditor && activeEditor.document, doc = (commandData && commandData.doc) || activeDoc, settings; if (doc && !doc.isSaving) { if (doc.isUntitled()) { if (doc === activeDoc) { settings = { selections: activeEditor.getSelections(), scrollPos: activeEditor.getScrollPos() }; } return _doSaveAs(doc, settings); } else { return doSave(doc); } } return $.Deferred().reject().promise(); }
javascript
{ "resource": "" }
q17068
handleFileQuit
train
function handleFileQuit(commandData) { return _handleWindowGoingAway( commandData, function () { brackets.app.quit(); }, function () { // if fail, don't exit: user canceled (or asked us to save changes first, but we failed to do so) brackets.app.abortQuit(); } ); }
javascript
{ "resource": "" }
q17069
_disableCache
train
function _disableCache() { var result = new $.Deferred(); if (brackets.inBrowser) { result.resolve(); } else { var port = brackets.app.getRemoteDebuggingPort ? brackets.app.getRemoteDebuggingPort() : 9234; Inspector.getDebuggableWindows("127.0.0.1", port) .fail(result.reject) .done(function (response) { var page = response[0]; if (!page || !page.webSocketDebuggerUrl) { result.reject(); return; } var _socket = new WebSocket(page.webSocketDebuggerUrl); // Disable the cache _socket.onopen = function _onConnect() { _socket.send(JSON.stringify({ id: 1, method: "Network.setCacheDisabled", params: { "cacheDisabled": true } })); }; // The first message will be the confirmation => disconnected to allow remote debugging of Brackets _socket.onmessage = function _onMessage(e) { _socket.close(); result.resolve(); }; // In case of an error _socket.onerror = result.reject; }); } return result.promise(); }
javascript
{ "resource": "" }
q17070
browserReload
train
function browserReload(href) { if (_isReloading) { return; } _isReloading = true; return CommandManager.execute(Commands.FILE_CLOSE_ALL, { promptOnly: true }).done(function () { // Give everyone a chance to save their state - but don't let any problems block // us from quitting try { ProjectManager.trigger("beforeAppClose"); } catch (ex) { console.error(ex); } // Disable the cache to make reloads work _disableCache().always(function () { // Remove all menus to assure every part of Brackets is reloaded _.forEach(Menus.getAllMenus(), function (value, key) { Menus.removeMenu(key); }); // If there's a fragment in both URLs, setting location.href won't actually reload var fragment = href.indexOf("#"); if (fragment !== -1) { href = href.substr(0, fragment); } // Defer for a more successful reload - issue #11539 setTimeout(function () { window.location.href = href; }, 1000); }); }).fail(function () { _isReloading = false; }); }
javascript
{ "resource": "" }
q17071
handleReload
train
function handleReload(loadWithoutExtensions) { var href = window.location.href, params = new UrlParams(); // Make sure the Reload Without User Extensions parameter is removed params.parse(); if (loadWithoutExtensions) { if (!params.get("reloadWithoutUserExts")) { params.put("reloadWithoutUserExts", true); } } else { if (params.get("reloadWithoutUserExts")) { params.remove("reloadWithoutUserExts"); } } if (href.indexOf("?") !== -1) { href = href.substring(0, href.indexOf("?")); } if (!params.isEmpty()) { href += "?" + params.toString(); } // Give Mac native menus extra time to update shortcut highlighting. // Prevents the menu highlighting from getting messed up after reload. window.setTimeout(function () { browserReload(href); }, 100); }
javascript
{ "resource": "" }
q17072
getTagAttributes
train
function getTagAttributes(tagName) { var tag; if (!cachedAttributes.hasOwnProperty(tagName)) { tag = tagData.tags[tagName]; cachedAttributes[tagName] = []; if (tag.attributes) { cachedAttributes[tagName] = cachedAttributes[tagName].concat(tag.attributes); } tag.attributeGroups.forEach(function (group) { if (tagData.attributeGroups.hasOwnProperty(group)) { cachedAttributes[tagName] = cachedAttributes[tagName].concat(tagData.attributeGroups[group]); } }); cachedAttributes[tagName] = _.uniq(cachedAttributes[tagName].sort(), true); } return cachedAttributes[tagName]; }
javascript
{ "resource": "" }
q17073
normalizeGradientExpressionForQuickview
train
function normalizeGradientExpressionForQuickview(expression) { if (expression.indexOf("px") > 0) { var paramStart = expression.indexOf("(") + 1, paramEnd = expression.lastIndexOf(")"), parameters = expression.substring(paramStart, paramEnd), params = splitStyleProperty(parameters), lowerBound = 0, upperBound = $previewContainer.width(), args, thisSize, i; // find lower bound for (i = 0; i < params.length; i++) { args = params[i].split(" "); if (hasLengthInPixels(args)) { thisSize = parseFloat(args[1]); upperBound = Math.max(upperBound, thisSize); // we really only care about converting negative // pixel values -- so take the smallest negative pixel // value and use that as baseline for display purposes if (thisSize < 0) { lowerBound = Math.min(lowerBound, thisSize); } } } // convert negative lower bound to positive and adjust all pixel values // so that -20px is now 0px and 100px is now 120px lowerBound = Math.abs(lowerBound); // Offset the upperbound by the lowerBound to give us a corrected context upperBound += lowerBound; // convert to % for (i = 0; i < params.length; i++) { args = params[i].split(" "); if (isGradientColorStop(args) && hasLengthInPixels(args)) { if (upperBound === 0) { thisSize = 0; } else { thisSize = ((parseFloat(args[1]) + lowerBound) / upperBound) * 100; } args[1] = thisSize + "%"; } params[i] = args.join(" "); } // put it back together. expression = expression.substring(0, paramStart) + params.join(", ") + expression.substring(paramEnd); } return expression; }
javascript
{ "resource": "" }
q17074
showPreview
train
function showPreview(editor, popover) { var token, cm; // Figure out which editor we are over if (!editor) { editor = getHoveredEditor(lastMousePos); } if (!editor || !editor._codeMirror) { hidePreview(); return; } cm = editor._codeMirror; // Find char mouse is over var pos = cm.coordsChar({left: lastMousePos.clientX, top: lastMousePos.clientY}); // No preview if mouse is past last char on line if (pos.ch >= editor.document.getLine(pos.line).length) { return; } if (popover) { popoverState = popover; } else { // Query providers and append to popoverState token = TokenUtils.getTokenAt(cm, pos); popoverState = $.extend({}, popoverState, queryPreviewProviders(editor, pos, token)); } if (popoverState && popoverState.start && popoverState.end) { popoverState.marker = cm.markText( popoverState.start, popoverState.end, {className: "quick-view-highlight"} ); $previewContent.append(popoverState.content); $previewContainer.show(); popoverState.visible = true; if (popoverState.onShow) { popoverState.onShow(); } else { positionPreview(editor, popoverState.xpos, popoverState.ytop, popoverState.ybot); } } }
javascript
{ "resource": "" }
q17075
getFunctionArgs
train
function getFunctionArgs(args) { if (args.length > 2) { var fnArgs = new Array(args.length - 2), i; for (i = 2; i < args.length; ++i) { fnArgs[i - 2] = args[i]; } return fnArgs; } return []; }
javascript
{ "resource": "" }
q17076
postMessageToBrackets
train
function postMessageToBrackets(messageId, requester) { if(!requesters[requester]) { for (var key in requesters) { requester = key; break; } } var msgObj = { fn: messageId, args: getFunctionArgs(arguments), requester: requester.toString() }; _domainManager.emitEvent('AutoUpdate', 'data', [msgObj]); }
javascript
{ "resource": "" }
q17077
validateChecksum
train
function validateChecksum(requester, params) { params = params || { filePath: installerPath, expectedChecksum: _updateParams.checksum }; var hash = crypto.createHash('sha256'), currentRequester = requester || ""; if (fs.existsSync(params.filePath)) { var stream = fs.createReadStream(params.filePath); stream.on('data', function (data) { hash.update(data); }); stream.on('end', function () { var calculatedChecksum = hash.digest('hex'), isValidChecksum = (params.expectedChecksum === calculatedChecksum), status; if (isValidChecksum) { if (process.platform === "darwin") { status = { valid: true, installerPath: installerPath, logFilePath: logFilePath, installStatusFilePath: installStatusFilePath }; } else if (process.platform === "win32") { status = { valid: true, installerPath: quoteAndConvert(installerPath, true), logFilePath: quoteAndConvert(logFilePath, true), installStatusFilePath: installStatusFilePath }; } } else { status = { valid: false, err: nodeErrorMessages.CHECKSUM_DID_NOT_MATCH }; } postMessageToBrackets(MessageIds.NOTIFY_VALIDATION_STATUS, currentRequester, status); }); } else { var status = { valid: false, err: nodeErrorMessages.INSTALLER_NOT_FOUND }; postMessageToBrackets(MessageIds.NOTIFY_VALIDATION_STATUS, currentRequester, status); } }
javascript
{ "resource": "" }
q17078
parseInstallerLog
train
function parseInstallerLog(filepath, searchstring, encoding, callback) { var line = ""; var searchFn = function searchFn(str) { var arr = str.split('\n'), lineNum, pos; for (lineNum = arr.length - 1; lineNum >= 0; lineNum--) { var searchStrNum; for (searchStrNum = 0; searchStrNum < searchstring.length; searchStrNum++) { pos = arr[lineNum].search(searchstring[searchStrNum]); if (pos !== -1) { line = arr[lineNum]; break; } } if (pos !== -1) { break; } } callback(line); }; fs.readFile(filepath, {"encoding": encoding}) .then(function (str) { return searchFn(str); }).catch(function () { callback(""); }); }
javascript
{ "resource": "" }
q17079
checkInstallerStatus
train
function checkInstallerStatus(requester, searchParams) { var installErrorStr = searchParams.installErrorStr, bracketsErrorStr = searchParams.bracketsErrorStr, updateDirectory = searchParams.updateDir, encoding = searchParams.encoding || "utf8", statusObj = {installError: ": BA_UN"}, logFileAvailable = false, currentRequester = requester || ""; var notifyBrackets = function notifyBrackets(errorline) { statusObj.installError = errorline || ": BA_UN"; postMessageToBrackets(MessageIds.NOTIFY_INSTALLATION_STATUS, currentRequester, statusObj); }; var parseLog = function (files) { files.forEach(function (file) { var fileExt = path.extname(path.basename(file)); if (fileExt === ".logs") { var fileName = path.basename(file), fileFullPath = updateDirectory + '/' + file; if (fileName.search("installStatus.logs") !== -1) { logFileAvailable = true; parseInstallerLog(fileFullPath, bracketsErrorStr, "utf8", notifyBrackets); } else if (fileName.search("update.logs") !== -1) { logFileAvailable = true; parseInstallerLog(fileFullPath, installErrorStr, encoding, notifyBrackets); } } }); if (!logFileAvailable) { postMessageToBrackets(MessageIds.NOTIFY_INSTALLATION_STATUS, currentRequester, statusObj); } }; fs.readdir(updateDirectory) .then(function (files) { return parseLog(files); }).catch(function () { postMessageToBrackets(MessageIds.NOTIFY_INSTALLATION_STATUS, currentRequester, statusObj); }); }
javascript
{ "resource": "" }
q17080
downloadInstaller
train
function downloadInstaller(requester, isInitialAttempt, updateParams) { updateParams = updateParams || _updateParams; var currentRequester = requester || ""; try { var ext = path.extname(updateParams.installerName); var localInstallerPath = path.resolve(updateDir, Date.now().toString() + ext), localInstallerFile = fs.createWriteStream(localInstallerPath), requestCompleted = true, readTimeOut = 180000; progress(request(updateParams.downloadURL, {timeout: readTimeOut}), {}) .on('progress', function (state) { var target = "retry-download"; if (isInitialAttempt) { target = "initial-download"; } var info = Math.floor(parseFloat(state.percent) * 100).toString() + '%'; var status = { target: target, spans: [{ id: "percent", val: info }] }; postMessageToBrackets(MessageIds.SHOW_STATUS_INFO, currentRequester, status); }) .on('error', function (err) { console.log("AutoUpdate : Download failed. Error occurred : " + err.toString()); requestCompleted = false; localInstallerFile.end(); var error = err.code === 'ESOCKETTIMEDOUT' || err.code === 'ENOTFOUND' ? nodeErrorMessages.NETWORK_SLOW_OR_DISCONNECTED : nodeErrorMessages.DOWNLOAD_ERROR; postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_FAILURE, currentRequester, error); }) .pipe(localInstallerFile) .on('close', function () { if (requestCompleted) { try { fs.renameSync(localInstallerPath, installerPath); postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_SUCCESS, currentRequester); } catch (e) { console.log("AutoUpdate : Download failed. Exception occurred : " + e.toString()); postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_FAILURE, currentRequester, nodeErrorMessages.DOWNLOAD_ERROR); } } }); } catch (e) { console.log("AutoUpdate : Download failed. Exception occurred : " + e.toString()); postMessageToBrackets(MessageIds.NOTIFY_DOWNLOAD_FAILURE, currentRequester, nodeErrorMessages.DOWNLOAD_ERROR); } }
javascript
{ "resource": "" }
q17081
performCleanup
train
function performCleanup(requester, filesToCache, notifyBack) { var currentRequester = requester || ""; function filterFilesAndNotify(files, filesToCacheArr, notifyBackToBrackets) { files.forEach(function (file) { var fileExt = path.extname(path.basename(file)); if (filesToCacheArr.indexOf(fileExt) < 0) { var fileFullPath = updateDir + '/' + file; try { fs.removeSync(fileFullPath); } catch (e) { console.log("AutoUpdate : Exception occured in removing ", fileFullPath, e); } } }); if (notifyBackToBrackets) { postMessageToBrackets(MessageIds.NOTIFY_SAFE_TO_DOWNLOAD, currentRequester); } } fs.stat(updateDir) .then(function (stats) { if (stats) { if (filesToCache) { fs.readdir(updateDir) .then(function (files) { filterFilesAndNotify(files, filesToCache, notifyBack); }) .catch(function (err) { console.log("AutoUpdate : Error in Reading Update Dir for Cleanup : " + err.toString()); postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE, currentRequester, nodeErrorMessages.UPDATEDIR_READ_FAILED); }); } else { fs.remove(updateDir) .then(function () { console.log('AutoUpdate : Update Directory in AppData Cleaned: Complete'); }) .catch(function (err) { console.log("AutoUpdate : Error in Cleaning Update Dir : " + err.toString()); postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE, currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED); }); } } }) .catch(function (err) { console.log("AutoUpdate : Error in Reading Update Dir stats for Cleanup : " + err.toString()); postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE, currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED); }); }
javascript
{ "resource": "" }
q17082
initializeState
train
function initializeState(requester, updateParams) { var currentRequester = requester || ""; _updateParams = updateParams; installerPath = path.resolve(updateDir, updateParams.installerName); postMessageToBrackets(MessageIds.NOTIFY_INITIALIZATION_COMPLETE, currentRequester); }
javascript
{ "resource": "" }
q17083
registerNodeFunctions
train
function registerNodeFunctions() { functionMap["node.downloadInstaller"] = downloadInstaller; functionMap["node.performCleanup"] = performCleanup; functionMap["node.validateInstaller"] = validateChecksum; functionMap["node.initializeState"] = initializeState; functionMap["node.checkInstallerStatus"] = checkInstallerStatus; functionMap["node.removeFromRequesters"] = removeFromRequesters; }
javascript
{ "resource": "" }
q17084
initNode
train
function initNode(initObj) { var resetUpdateProgres = false; if (!isNodeDomainInitialized) { MessageIds = initObj.messageIds; updateDir = path.resolve(initObj.updateDir); logFilePath = path.resolve(updateDir, logFile); installStatusFilePath = path.resolve(updateDir, installStatusFile); registerNodeFunctions(); isNodeDomainInitialized = true; resetUpdateProgres = true; } postMessageToBrackets(MessageIds.NODE_DOMAIN_INITIALIZED, initObj.requester.toString(), resetUpdateProgres); requesters[initObj.requester.toString()] = true; postMessageToBrackets(MessageIds.REGISTER_BRACKETS_FUNCTIONS, initObj.requester.toString()); }
javascript
{ "resource": "" }
q17085
receiveMessageFromBrackets
train
function receiveMessageFromBrackets(msgObj) { var argList = msgObj.args; argList.unshift(msgObj.requester || ""); functionMap[msgObj.fn].apply(null, argList); }
javascript
{ "resource": "" }
q17086
init
train
function init(domainManager) { if (!domainManager.hasDomain("AutoUpdate")) { domainManager.registerDomain("AutoUpdate", { major: 0, minor: 1 }); } _domainManager = domainManager; domainManager.registerCommand( "AutoUpdate", "initNode", initNode, true, "Initializes node for the auto update", [ { name: "initObj", type: "object", description: "json object containing init information" } ], [] ); domainManager.registerCommand( "AutoUpdate", "data", receiveMessageFromBrackets, true, "Receives messages from brackets", [ { name: "msgObj", type: "object", description: "json object containing message info" } ], [] ); domainManager.registerEvent( "AutoUpdate", "data", [ { name: "msgObj", type: "object", description: "json object containing message info to pass to brackets" } ] ); }
javascript
{ "resource": "" }
q17087
_buildPreferencesContext
train
function _buildPreferencesContext(fullPath) { return PreferencesManager._buildContext(fullPath, fullPath ? LanguageManager.getLanguageForPath(fullPath).getId() : undefined); }
javascript
{ "resource": "" }
q17088
_onKeyEvent
train
function _onKeyEvent(instance, event) { self.trigger("keyEvent", self, event); // deprecated self.trigger(event.type, self, event); return event.defaultPrevented; // false tells CodeMirror we didn't eat the event }
javascript
{ "resource": "" }
q17089
format
train
function format(str) { // arguments[0] is the base string, so we need to adjust index values here var args = [].slice.call(arguments, 1); return str.replace(/\{(\d+)\}/g, function (match, num) { return typeof args[num] !== "undefined" ? args[num] : match; }); }
javascript
{ "resource": "" }
q17090
breakableUrl
train
function breakableUrl(url) { // This is for displaying in UI, so always want it escaped var escUrl = _.escape(url); // Inject zero-width space character (U+200B) near path separators (/) to allow line breaking there return escUrl.replace( new RegExp(regexEscape("/"), "g"), "/" + "&#8203;" ); }
javascript
{ "resource": "" }
q17091
prettyPrintBytes
train
function prettyPrintBytes(bytes, precision) { var kilobyte = 1024, megabyte = kilobyte * 1024, gigabyte = megabyte * 1024, terabyte = gigabyte * 1024, returnVal = bytes; if ((bytes >= 0) && (bytes < kilobyte)) { returnVal = bytes + " B"; } else if (bytes < megabyte) { returnVal = (bytes / kilobyte).toFixed(precision) + " KB"; } else if (bytes < gigabyte) { returnVal = (bytes / megabyte).toFixed(precision) + " MB"; } else if (bytes < terabyte) { returnVal = (bytes / gigabyte).toFixed(precision) + " GB"; } else if (bytes >= terabyte) { return (bytes / terabyte).toFixed(precision) + " TB"; } return returnVal; }
javascript
{ "resource": "" }
q17092
truncate
train
function truncate(str, len) { // Truncate text to specified length if (str.length > len) { str = str.substr(0, len); // To prevent awkwardly truncating in the middle of a word, // attempt to truncate at the end of the last whole word var lastSpaceChar = str.lastIndexOf(" "); if (lastSpaceChar < len && lastSpaceChar > -1) { str = str.substr(0, lastSpaceChar); } return str; } }
javascript
{ "resource": "" }
q17093
isInteger
train
function isInteger(value) { // Validate value is a number if (typeof (value) !== "number" || isNaN(parseInt(value, 10))) { return false; } // Validate number is an integer if (Math.floor(value) !== value) { return false; } // Validate number is finite if (!isFinite(value)) { return false; } return true; }
javascript
{ "resource": "" }
q17094
isIntegerInRange
train
function isIntegerInRange(value, lowerLimit, upperLimit) { // Validate value is an integer if (!isInteger(value)) { return false; } // Validate integer is in range var hasLowerLimt = (typeof (lowerLimit) === "number"), hasUpperLimt = (typeof (upperLimit) === "number"); return ((!hasLowerLimt || value >= lowerLimit) && (!hasUpperLimt || value <= upperLimit)); }
javascript
{ "resource": "" }
q17095
TextRange
train
function TextRange(document, startLine, endLine) { this.startLine = startLine; this.endLine = endLine; this.document = document; document.addRef(); // store this-bound versions of listeners so we can remove them later this._handleDocumentChange = this._handleDocumentChange.bind(this); this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this); document.on("change", this._handleDocumentChange); document.on("deleted", this._handleDocumentDeleted); }
javascript
{ "resource": "" }
q17096
getInfoAtPos
train
function getInfoAtPos(editor, constPos) { // We're going to be changing pos a lot, but we don't want to mess up // the pos the caller passed in so we use extend to make a safe copy of it. var pos = $.extend({}, constPos), ctx = TokenUtils.getInitialContext(editor._codeMirror, pos), mode = editor.getModeForSelection(); // Check if this is inside a style block or in a css/less document. if (mode !== "css" && mode !== "text/x-scss" && mode !== "text/x-less") { return createInfo(); } // Context from the current editor will have htmlState if we are in css mode // and in attribute value state of a tag with attribute name style if (ctx.token.state.htmlState && (!ctx.token.state.localMode || ctx.token.state.localMode.name !== "css")) { // tagInfo is required to aquire the style attr value var tagInfo = HTMLUtils.getTagInfo(editor, pos, true), // To be used as relative character position offset = tagInfo.position.offset; /** * We will use this CM to cook css context in case of style attribute value * as CM in htmlmixed mode doesn't yet identify this as css context. We provide * a no-op display function to run CM without a DOM head. */ var _contextCM = new CodeMirror(function () {}, { value: "{" + tagInfo.attr.value.replace(/(^")|("$)/g, ""), mode: "css" }); ctx = TokenUtils.getInitialContext(_contextCM, {line: 0, ch: offset + 1}); } if (_isInPropName(ctx)) { return _getPropNameInfo(ctx); } if (_isInPropValue(ctx)) { return _getRuleInfoStartingFromPropValue(ctx, ctx.editor); } if (_isInAtRule(ctx)) { return _getImportUrlInfo(ctx, editor); } return createInfo(); }
javascript
{ "resource": "" }
q17097
getCompleteSelectors
train
function getCompleteSelectors(info, useGroup) { if (info.parentSelectors) { // Show parents with / separators. var completeSelectors = info.parentSelectors + " / "; if (useGroup && info.selectorGroup) { completeSelectors += info.selectorGroup; } else { completeSelectors += info.selector; } return completeSelectors; } else if (useGroup && info.selectorGroup) { return info.selectorGroup; } return info.selector; }
javascript
{ "resource": "" }
q17098
_getSelectorInFinalCSSForm
train
function _getSelectorInFinalCSSForm(selectorArray) { var finalSelectorArray = [""], parentSelectorArray = [], group = []; _.forEach(selectorArray, function (selector) { selector = _stripAtRules(selector); group = selector.split(","); parentSelectorArray = []; _.forEach(group, function (cs) { var ampersandIndex = cs.indexOf("&"); _.forEach(finalSelectorArray, function (ps) { if (ampersandIndex === -1) { cs = _stripAtRules(cs); if (ps.length && cs.length) { ps += " "; } ps += cs; } else { // Replace all instances of & with regexp ps = _stripAtRules(cs.replace(/&/g, ps)); } parentSelectorArray.push(ps); }); }); finalSelectorArray = parentSelectorArray; }); return finalSelectorArray.join(", "); }
javascript
{ "resource": "" }
q17099
_findAllMatchingSelectorsInText
train
function _findAllMatchingSelectorsInText(text, selector, mode) { var allSelectors = extractAllSelectors(text, mode); var result = []; // For now, we only match the rightmost simple selector, and ignore // attribute selectors and pseudo selectors var classOrIdSelector = selector[0] === "." || selector[0] === "#"; // Escape initial "." in selector, if present. if (selector[0] === ".") { selector = "\\" + selector; } if (!classOrIdSelector) { // Tag selectors must have nothing, whitespace, or a combinator before it. selector = "(^|[\\s>+~])" + selector; } var re = new RegExp(selector + "(\\[[^\\]]*\\]|:{1,2}[\\w-()]+|\\.[\\w-]+|#[\\w-]+)*\\s*$", classOrIdSelector ? "" : "i"); allSelectors.forEach(function (entry) { var actualSelector = entry.selector; if (entry.selector.indexOf("&") !== -1 && entry.parentSelectors) { var selectorArray = entry.parentSelectors.split(" / "); selectorArray.push(entry.selector); actualSelector = _getSelectorInFinalCSSForm(selectorArray); } if (actualSelector.search(re) !== -1) { result.push(entry); } else if (!classOrIdSelector) { // Special case for tag selectors - match "*" as the rightmost character if (/\*\s*$/.test(actualSelector)) { result.push(entry); } } }); return result; }
javascript
{ "resource": "" }