id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
2,000
adobe/brackets
src/utils/ExtensionUtils.js
parseLessCode
function parseLessCode(code, url) { var result = new $.Deferred(), options; if (url) { var dir = url.slice(0, url.lastIndexOf("/") + 1); options = { filename: url, rootpath: dir }; if (isAbsolutePathOrUrl(url)) { options.currentFileInfo = { currentDirectory: dir, entryPath: dir, filename: url, rootFilename: url, rootpath: dir }; } } less.render(code, options, function onParse(err, tree) { if (err) { result.reject(err); } else { result.resolve(tree.css); } }); return result.promise(); }
javascript
function parseLessCode(code, url) { var result = new $.Deferred(), options; if (url) { var dir = url.slice(0, url.lastIndexOf("/") + 1); options = { filename: url, rootpath: dir }; if (isAbsolutePathOrUrl(url)) { options.currentFileInfo = { currentDirectory: dir, entryPath: dir, filename: url, rootFilename: url, rootpath: dir }; } } less.render(code, options, function onParse(err, tree) { if (err) { result.reject(err); } else { result.resolve(tree.css); } }); return result.promise(); }
[ "function", "parseLessCode", "(", "code", ",", "url", ")", "{", "var", "result", "=", "new", "$", ".", "Deferred", "(", ")", ",", "options", ";", "if", "(", "url", ")", "{", "var", "dir", "=", "url", ".", "slice", "(", "0", ",", "url", ".", "lastIndexOf", "(", "\"/\"", ")", "+", "1", ")", ";", "options", "=", "{", "filename", ":", "url", ",", "rootpath", ":", "dir", "}", ";", "if", "(", "isAbsolutePathOrUrl", "(", "url", ")", ")", "{", "options", ".", "currentFileInfo", "=", "{", "currentDirectory", ":", "dir", ",", "entryPath", ":", "dir", ",", "filename", ":", "url", ",", "rootFilename", ":", "url", ",", "rootpath", ":", "dir", "}", ";", "}", "}", "less", ".", "render", "(", "code", ",", "options", ",", "function", "onParse", "(", "err", ",", "tree", ")", "{", "if", "(", "err", ")", "{", "result", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "result", ".", "resolve", "(", "tree", ".", "css", ")", ";", "}", "}", ")", ";", "return", "result", ".", "promise", "(", ")", ";", "}" ]
Parses LESS code and returns a promise that resolves with plain CSS code. Pass the {@link url} argument to resolve relative URLs contained in the code. Make sure URLs in the code are wrapped in quotes, like so: background-image: url("image.png"); @param {!string} code LESS code to parse @param {?string} url URL to the file containing the code @return {!$.Promise} A promise object that is resolved with CSS code if the LESS code can be parsed
[ "Parses", "LESS", "code", "and", "returns", "a", "promise", "that", "resolves", "with", "plain", "CSS", "code", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ExtensionUtils.js#L96-L128
2,001
adobe/brackets
src/utils/ExtensionUtils.js
getModulePath
function getModulePath(module, path) { var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1); if (path) { modulePath += path; } return modulePath; }
javascript
function getModulePath(module, path) { var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1); if (path) { modulePath += path; } return modulePath; }
[ "function", "getModulePath", "(", "module", ",", "path", ")", "{", "var", "modulePath", "=", "module", ".", "uri", ".", "substr", "(", "0", ",", "module", ".", "uri", ".", "lastIndexOf", "(", "\"/\"", ")", "+", "1", ")", ";", "if", "(", "path", ")", "{", "modulePath", "+=", "path", ";", "}", "return", "modulePath", ";", "}" ]
Returns a path to an extension module. @param {!module} module Module provided by RequireJS @param {?string} path Relative path from the extension folder to a file @return {!string} The path to the module's folder
[ "Returns", "a", "path", "to", "an", "extension", "module", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ExtensionUtils.js#L137-L144
2,002
adobe/brackets
src/utils/ExtensionUtils.js
getModuleUrl
function getModuleUrl(module, path) { var url = encodeURI(getModulePath(module, path)); // On Windows, $.get() fails if the url is a full pathname. To work around this, // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname, // but *doesn't* work if it is prepended with "file://". Go figure. // However, the prefix "file://localhost" does work. if (brackets.platform === "win" && url.indexOf(":") !== -1) { url = "file:///" + url; } return url; }
javascript
function getModuleUrl(module, path) { var url = encodeURI(getModulePath(module, path)); // On Windows, $.get() fails if the url is a full pathname. To work around this, // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname, // but *doesn't* work if it is prepended with "file://". Go figure. // However, the prefix "file://localhost" does work. if (brackets.platform === "win" && url.indexOf(":") !== -1) { url = "file:///" + url; } return url; }
[ "function", "getModuleUrl", "(", "module", ",", "path", ")", "{", "var", "url", "=", "encodeURI", "(", "getModulePath", "(", "module", ",", "path", ")", ")", ";", "// On Windows, $.get() fails if the url is a full pathname. To work around this,", "// prepend \"file:///\". On the Mac, $.get() works fine if the url is a full pathname,", "// but *doesn't* work if it is prepended with \"file://\". Go figure.", "// However, the prefix \"file://localhost\" does work.", "if", "(", "brackets", ".", "platform", "===", "\"win\"", "&&", "url", ".", "indexOf", "(", "\":\"", ")", "!==", "-", "1", ")", "{", "url", "=", "\"file:///\"", "+", "url", ";", "}", "return", "url", ";", "}" ]
Returns a URL to an extension module. @param {!module} module Module provided by RequireJS @param {?string} path Relative path from the extension folder to a file @return {!string} The URL to the module's folder
[ "Returns", "a", "URL", "to", "an", "extension", "module", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ExtensionUtils.js#L153-L165
2,003
adobe/brackets
src/utils/ExtensionUtils.js
loadFile
function loadFile(module, path) { var url = PathUtils.isAbsoluteUrl(path) ? path : getModuleUrl(module, path), promise = $.get(url); return promise; }
javascript
function loadFile(module, path) { var url = PathUtils.isAbsoluteUrl(path) ? path : getModuleUrl(module, path), promise = $.get(url); return promise; }
[ "function", "loadFile", "(", "module", ",", "path", ")", "{", "var", "url", "=", "PathUtils", ".", "isAbsoluteUrl", "(", "path", ")", "?", "path", ":", "getModuleUrl", "(", "module", ",", "path", ")", ",", "promise", "=", "$", ".", "get", "(", "url", ")", ";", "return", "promise", ";", "}" ]
Performs a GET request using a path relative to an extension module. The resulting URL can be retrieved in the resolve callback by accessing @param {!module} module Module provided by RequireJS @param {!string} path Relative path from the extension folder to a file @return {!$.Promise} A promise object that is resolved with the contents of the requested file
[ "Performs", "a", "GET", "request", "using", "a", "path", "relative", "to", "an", "extension", "module", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ExtensionUtils.js#L176-L181
2,004
adobe/brackets
src/utils/ExtensionUtils.js
loadMetadata
function loadMetadata(folder) { var packageJSONFile = FileSystem.getFileForPath(folder + "/package.json"), disabledFile = FileSystem.getFileForPath(folder + "/.disabled"), baseName = FileUtils.getBaseName(folder), result = new $.Deferred(), jsonPromise = new $.Deferred(), disabledPromise = new $.Deferred(), json, disabled; FileUtils.readAsText(packageJSONFile) .then(function (text) { try { json = JSON.parse(text); jsonPromise.resolve(); } catch (e) { jsonPromise.reject(); } }) .fail(jsonPromise.reject); disabledFile.exists(function (err, exists) { if (err) { disabled = false; } else { disabled = exists; } var defaultDisabled = PreferencesManager.get("extensions.default.disabled"); if (Array.isArray(defaultDisabled) && defaultDisabled.indexOf(folder) !== -1) { console.warn("Default extension has been disabled on startup: " + baseName); disabled = true; } disabledPromise.resolve(); }); Async.waitForAll([jsonPromise, disabledPromise]) .always(function () { if (!json) { // if we don't have any metadata for the extension // we should still create an empty one, so we can attach // disabled property on it in case it's disabled json = { name: baseName }; } json.disabled = disabled; result.resolve(json); }); return result.promise(); }
javascript
function loadMetadata(folder) { var packageJSONFile = FileSystem.getFileForPath(folder + "/package.json"), disabledFile = FileSystem.getFileForPath(folder + "/.disabled"), baseName = FileUtils.getBaseName(folder), result = new $.Deferred(), jsonPromise = new $.Deferred(), disabledPromise = new $.Deferred(), json, disabled; FileUtils.readAsText(packageJSONFile) .then(function (text) { try { json = JSON.parse(text); jsonPromise.resolve(); } catch (e) { jsonPromise.reject(); } }) .fail(jsonPromise.reject); disabledFile.exists(function (err, exists) { if (err) { disabled = false; } else { disabled = exists; } var defaultDisabled = PreferencesManager.get("extensions.default.disabled"); if (Array.isArray(defaultDisabled) && defaultDisabled.indexOf(folder) !== -1) { console.warn("Default extension has been disabled on startup: " + baseName); disabled = true; } disabledPromise.resolve(); }); Async.waitForAll([jsonPromise, disabledPromise]) .always(function () { if (!json) { // if we don't have any metadata for the extension // we should still create an empty one, so we can attach // disabled property on it in case it's disabled json = { name: baseName }; } json.disabled = disabled; result.resolve(json); }); return result.promise(); }
[ "function", "loadMetadata", "(", "folder", ")", "{", "var", "packageJSONFile", "=", "FileSystem", ".", "getFileForPath", "(", "folder", "+", "\"/package.json\"", ")", ",", "disabledFile", "=", "FileSystem", ".", "getFileForPath", "(", "folder", "+", "\"/.disabled\"", ")", ",", "baseName", "=", "FileUtils", ".", "getBaseName", "(", "folder", ")", ",", "result", "=", "new", "$", ".", "Deferred", "(", ")", ",", "jsonPromise", "=", "new", "$", ".", "Deferred", "(", ")", ",", "disabledPromise", "=", "new", "$", ".", "Deferred", "(", ")", ",", "json", ",", "disabled", ";", "FileUtils", ".", "readAsText", "(", "packageJSONFile", ")", ".", "then", "(", "function", "(", "text", ")", "{", "try", "{", "json", "=", "JSON", ".", "parse", "(", "text", ")", ";", "jsonPromise", ".", "resolve", "(", ")", ";", "}", "catch", "(", "e", ")", "{", "jsonPromise", ".", "reject", "(", ")", ";", "}", "}", ")", ".", "fail", "(", "jsonPromise", ".", "reject", ")", ";", "disabledFile", ".", "exists", "(", "function", "(", "err", ",", "exists", ")", "{", "if", "(", "err", ")", "{", "disabled", "=", "false", ";", "}", "else", "{", "disabled", "=", "exists", ";", "}", "var", "defaultDisabled", "=", "PreferencesManager", ".", "get", "(", "\"extensions.default.disabled\"", ")", ";", "if", "(", "Array", ".", "isArray", "(", "defaultDisabled", ")", "&&", "defaultDisabled", ".", "indexOf", "(", "folder", ")", "!==", "-", "1", ")", "{", "console", ".", "warn", "(", "\"Default extension has been disabled on startup: \"", "+", "baseName", ")", ";", "disabled", "=", "true", ";", "}", "disabledPromise", ".", "resolve", "(", ")", ";", "}", ")", ";", "Async", ".", "waitForAll", "(", "[", "jsonPromise", ",", "disabledPromise", "]", ")", ".", "always", "(", "function", "(", ")", "{", "if", "(", "!", "json", ")", "{", "// if we don't have any metadata for the extension", "// we should still create an empty one, so we can attach", "// disabled property on it in case it's disabled", "json", "=", "{", "name", ":", "baseName", "}", ";", "}", "json", ".", "disabled", "=", "disabled", ";", "result", ".", "resolve", "(", "json", ")", ";", "}", ")", ";", "return", "result", ".", "promise", "(", ")", ";", "}" ]
Loads the package.json file in the given extension folder as well as any additional metadata. If there's a .disabled file in the extension directory, then the content of package.json will be augmented with disabled property set to true. It will override whatever value of disabled might be set. @param {string} folder The extension folder. @return {$.Promise} A promise object that is resolved with the parsed contents of the package.json file, or rejected if there is no package.json with the boolean indicating whether .disabled file exists.
[ "Loads", "the", "package", ".", "json", "file", "in", "the", "given", "extension", "folder", "as", "well", "as", "any", "additional", "metadata", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ExtensionUtils.js#L241-L289
2,005
adobe/brackets
src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js
_markTags
function _markTags(cm, node) { node.children.forEach(function (childNode) { if (childNode.isElement()) { _markTags(cm, childNode); } }); var mark = cm.markText(node.startPos, node.endPos); mark.tagID = node.tagID; }
javascript
function _markTags(cm, node) { node.children.forEach(function (childNode) { if (childNode.isElement()) { _markTags(cm, childNode); } }); var mark = cm.markText(node.startPos, node.endPos); mark.tagID = node.tagID; }
[ "function", "_markTags", "(", "cm", ",", "node", ")", "{", "node", ".", "children", ".", "forEach", "(", "function", "(", "childNode", ")", "{", "if", "(", "childNode", ".", "isElement", "(", ")", ")", "{", "_markTags", "(", "cm", ",", "childNode", ")", ";", "}", "}", ")", ";", "var", "mark", "=", "cm", ".", "markText", "(", "node", ".", "startPos", ",", "node", ".", "endPos", ")", ";", "mark", ".", "tagID", "=", "node", ".", "tagID", ";", "}" ]
Recursively walks the SimpleDOM starting at node and marking all tags in the CodeMirror instance. The more useful interface is the _markTextFromDOM function which clears existing marks before calling this function to create new ones. @param {CodeMirror} cm CodeMirror instance in which to mark tags @param {Object} node SimpleDOM node to use as the root for marking
[ "Recursively", "walks", "the", "SimpleDOM", "starting", "at", "node", "and", "marking", "all", "tags", "in", "the", "CodeMirror", "instance", ".", "The", "more", "useful", "interface", "is", "the", "_markTextFromDOM", "function", "which", "clears", "existing", "marks", "before", "calling", "this", "function", "to", "create", "new", "ones", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js#L192-L200
2,006
adobe/brackets
src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js
_markTextFromDOM
function _markTextFromDOM(editor, dom) { var cm = editor._codeMirror; // Remove existing marks var marks = cm.getAllMarks(); cm.operation(function () { marks.forEach(function (mark) { if (mark.hasOwnProperty("tagID")) { mark.clear(); } }); }); // Mark _markTags(cm, dom); }
javascript
function _markTextFromDOM(editor, dom) { var cm = editor._codeMirror; // Remove existing marks var marks = cm.getAllMarks(); cm.operation(function () { marks.forEach(function (mark) { if (mark.hasOwnProperty("tagID")) { mark.clear(); } }); }); // Mark _markTags(cm, dom); }
[ "function", "_markTextFromDOM", "(", "editor", ",", "dom", ")", "{", "var", "cm", "=", "editor", ".", "_codeMirror", ";", "// Remove existing marks", "var", "marks", "=", "cm", ".", "getAllMarks", "(", ")", ";", "cm", ".", "operation", "(", "function", "(", ")", "{", "marks", ".", "forEach", "(", "function", "(", "mark", ")", "{", "if", "(", "mark", ".", "hasOwnProperty", "(", "\"tagID\"", ")", ")", "{", "mark", ".", "clear", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "// Mark", "_markTags", "(", "cm", ",", "dom", ")", ";", "}" ]
Clears the marks from the document and creates new ones. @param {Editor} editor Editor object holding this document @param {Object} dom SimpleDOM root object that contains the parsed structure
[ "Clears", "the", "marks", "from", "the", "document", "and", "creates", "new", "ones", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js#L208-L223
2,007
adobe/brackets
src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js
scanDocument
function scanDocument(doc) { if (!_cachedValues.hasOwnProperty(doc.file.fullPath)) { // TODO: this doesn't seem to be correct any more. The DOM should never be "dirty" (i.e., out of sync // with the editor) unless the doc is invalid. // $(doc).on("change.htmlInstrumentation", function () { // if (_cachedValues[doc.file.fullPath]) { // _cachedValues[doc.file.fullPath].dirty = true; // } // }); // Assign to cache, but don't set a value yet _cachedValues[doc.file.fullPath] = null; } var cachedValue = _cachedValues[doc.file.fullPath]; // TODO: No longer look at doc or cached value "dirty" settings, because even if the doc is dirty, the dom // should generally be up to date unless the HTML is invalid. (However, the node offsets will be dirty of // the dom was incrementally updated - we should note that somewhere.) if (cachedValue && !cachedValue.invalid && cachedValue.timestamp === doc.diskTimestamp) { return cachedValue.dom; } var text = doc.getText(), dom = HTMLSimpleDOM.build(text); if (dom) { // Cache results _cachedValues[doc.file.fullPath] = { timestamp: doc.diskTimestamp, dom: dom, dirty: false }; // Note that this was a full build, so we know that we can trust the node start/end offsets. dom.fullBuild = true; } return dom; }
javascript
function scanDocument(doc) { if (!_cachedValues.hasOwnProperty(doc.file.fullPath)) { // TODO: this doesn't seem to be correct any more. The DOM should never be "dirty" (i.e., out of sync // with the editor) unless the doc is invalid. // $(doc).on("change.htmlInstrumentation", function () { // if (_cachedValues[doc.file.fullPath]) { // _cachedValues[doc.file.fullPath].dirty = true; // } // }); // Assign to cache, but don't set a value yet _cachedValues[doc.file.fullPath] = null; } var cachedValue = _cachedValues[doc.file.fullPath]; // TODO: No longer look at doc or cached value "dirty" settings, because even if the doc is dirty, the dom // should generally be up to date unless the HTML is invalid. (However, the node offsets will be dirty of // the dom was incrementally updated - we should note that somewhere.) if (cachedValue && !cachedValue.invalid && cachedValue.timestamp === doc.diskTimestamp) { return cachedValue.dom; } var text = doc.getText(), dom = HTMLSimpleDOM.build(text); if (dom) { // Cache results _cachedValues[doc.file.fullPath] = { timestamp: doc.diskTimestamp, dom: dom, dirty: false }; // Note that this was a full build, so we know that we can trust the node start/end offsets. dom.fullBuild = true; } return dom; }
[ "function", "scanDocument", "(", "doc", ")", "{", "if", "(", "!", "_cachedValues", ".", "hasOwnProperty", "(", "doc", ".", "file", ".", "fullPath", ")", ")", "{", "// TODO: this doesn't seem to be correct any more. The DOM should never be \"dirty\" (i.e., out of sync", "// with the editor) unless the doc is invalid.", "// $(doc).on(\"change.htmlInstrumentation\", function () {", "// if (_cachedValues[doc.file.fullPath]) {", "// _cachedValues[doc.file.fullPath].dirty = true;", "// }", "// });", "// Assign to cache, but don't set a value yet", "_cachedValues", "[", "doc", ".", "file", ".", "fullPath", "]", "=", "null", ";", "}", "var", "cachedValue", "=", "_cachedValues", "[", "doc", ".", "file", ".", "fullPath", "]", ";", "// TODO: No longer look at doc or cached value \"dirty\" settings, because even if the doc is dirty, the dom", "// should generally be up to date unless the HTML is invalid. (However, the node offsets will be dirty of", "// the dom was incrementally updated - we should note that somewhere.)", "if", "(", "cachedValue", "&&", "!", "cachedValue", ".", "invalid", "&&", "cachedValue", ".", "timestamp", "===", "doc", ".", "diskTimestamp", ")", "{", "return", "cachedValue", ".", "dom", ";", "}", "var", "text", "=", "doc", ".", "getText", "(", ")", ",", "dom", "=", "HTMLSimpleDOM", ".", "build", "(", "text", ")", ";", "if", "(", "dom", ")", "{", "// Cache results", "_cachedValues", "[", "doc", ".", "file", ".", "fullPath", "]", "=", "{", "timestamp", ":", "doc", ".", "diskTimestamp", ",", "dom", ":", "dom", ",", "dirty", ":", "false", "}", ";", "// Note that this was a full build, so we know that we can trust the node start/end offsets.", "dom", ".", "fullBuild", "=", "true", ";", "}", "return", "dom", ";", "}" ]
Parses the document, returning an HTMLSimpleDOM structure and caching it as the initial state of the document. Will return a cached copy of the DOM if the document hasn't changed since the last time scanDocument was called. This is called by generateInstrumentedHTML(), but it can be useful to call it ahead of time so the DOM is cached and doesn't need to be rescanned when the instrumented HTML is requested by the browser. @param {Document} doc The doc to scan. @return {Object} Root DOM node of the document.
[ "Parses", "the", "document", "returning", "an", "HTMLSimpleDOM", "structure", "and", "caching", "it", "as", "the", "initial", "state", "of", "the", "document", ".", "Will", "return", "a", "cached", "copy", "of", "the", "DOM", "if", "the", "document", "hasn", "t", "changed", "since", "the", "last", "time", "scanDocument", "was", "called", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js#L677-L714
2,008
adobe/brackets
src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js
walk
function walk(node) { if (node.tag) { var attrText = " data-brackets-id='" + node.tagID + "'"; // If the dom was fully rebuilt, use its offsets. Otherwise, use the marks in the // associated editor, since they'll be more up to date. var startOffset; if (dom.fullBuild) { startOffset = node.start; } else { var mark = markCache[node.tagID]; if (mark) { startOffset = editor._codeMirror.indexFromPos(mark.range.from); } else { console.warn("generateInstrumentedHTML(): couldn't find existing mark for tagID " + node.tagID); startOffset = node.start; } } // Insert the attribute as the first attribute in the tag. var insertIndex = startOffset + node.tag.length + 1; gen += orig.substr(lastIndex, insertIndex - lastIndex) + attrText; lastIndex = insertIndex; // If we have a script to inject and this is the head tag, inject it immediately // after the open tag. if (remoteScript && !remoteScriptInserted && node.tag === "head") { insertIndex = node.openEnd; gen += orig.substr(lastIndex, insertIndex - lastIndex) + remoteScript; lastIndex = insertIndex; remoteScriptInserted = true; } } if (node.isElement()) { node.children.forEach(walk); } }
javascript
function walk(node) { if (node.tag) { var attrText = " data-brackets-id='" + node.tagID + "'"; // If the dom was fully rebuilt, use its offsets. Otherwise, use the marks in the // associated editor, since they'll be more up to date. var startOffset; if (dom.fullBuild) { startOffset = node.start; } else { var mark = markCache[node.tagID]; if (mark) { startOffset = editor._codeMirror.indexFromPos(mark.range.from); } else { console.warn("generateInstrumentedHTML(): couldn't find existing mark for tagID " + node.tagID); startOffset = node.start; } } // Insert the attribute as the first attribute in the tag. var insertIndex = startOffset + node.tag.length + 1; gen += orig.substr(lastIndex, insertIndex - lastIndex) + attrText; lastIndex = insertIndex; // If we have a script to inject and this is the head tag, inject it immediately // after the open tag. if (remoteScript && !remoteScriptInserted && node.tag === "head") { insertIndex = node.openEnd; gen += orig.substr(lastIndex, insertIndex - lastIndex) + remoteScript; lastIndex = insertIndex; remoteScriptInserted = true; } } if (node.isElement()) { node.children.forEach(walk); } }
[ "function", "walk", "(", "node", ")", "{", "if", "(", "node", ".", "tag", ")", "{", "var", "attrText", "=", "\" data-brackets-id='\"", "+", "node", ".", "tagID", "+", "\"'\"", ";", "// If the dom was fully rebuilt, use its offsets. Otherwise, use the marks in the", "// associated editor, since they'll be more up to date.", "var", "startOffset", ";", "if", "(", "dom", ".", "fullBuild", ")", "{", "startOffset", "=", "node", ".", "start", ";", "}", "else", "{", "var", "mark", "=", "markCache", "[", "node", ".", "tagID", "]", ";", "if", "(", "mark", ")", "{", "startOffset", "=", "editor", ".", "_codeMirror", ".", "indexFromPos", "(", "mark", ".", "range", ".", "from", ")", ";", "}", "else", "{", "console", ".", "warn", "(", "\"generateInstrumentedHTML(): couldn't find existing mark for tagID \"", "+", "node", ".", "tagID", ")", ";", "startOffset", "=", "node", ".", "start", ";", "}", "}", "// Insert the attribute as the first attribute in the tag.", "var", "insertIndex", "=", "startOffset", "+", "node", ".", "tag", ".", "length", "+", "1", ";", "gen", "+=", "orig", ".", "substr", "(", "lastIndex", ",", "insertIndex", "-", "lastIndex", ")", "+", "attrText", ";", "lastIndex", "=", "insertIndex", ";", "// If we have a script to inject and this is the head tag, inject it immediately", "// after the open tag.", "if", "(", "remoteScript", "&&", "!", "remoteScriptInserted", "&&", "node", ".", "tag", "===", "\"head\"", ")", "{", "insertIndex", "=", "node", ".", "openEnd", ";", "gen", "+=", "orig", ".", "substr", "(", "lastIndex", ",", "insertIndex", "-", "lastIndex", ")", "+", "remoteScript", ";", "lastIndex", "=", "insertIndex", ";", "remoteScriptInserted", "=", "true", ";", "}", "}", "if", "(", "node", ".", "isElement", "(", ")", ")", "{", "node", ".", "children", ".", "forEach", "(", "walk", ")", ";", "}", "}" ]
Walk through the dom nodes and insert the 'data-brackets-id' attribute at the end of the open tag
[ "Walk", "through", "the", "dom", "nodes", "and", "insert", "the", "data", "-", "brackets", "-", "id", "attribute", "at", "the", "end", "of", "the", "open", "tag" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation.js#L762-L799
2,009
adobe/brackets
src/extensions/default/JavaScriptCodeHints/main.js
setCachedHintContext
function setCachedHintContext(hints, cursor, type, token) { cachedHints = hints; cachedCursor = cursor; cachedType = type; cachedToken = token; }
javascript
function setCachedHintContext(hints, cursor, type, token) { cachedHints = hints; cachedCursor = cursor; cachedType = type; cachedToken = token; }
[ "function", "setCachedHintContext", "(", "hints", ",", "cursor", ",", "type", ",", "token", ")", "{", "cachedHints", "=", "hints", ";", "cachedCursor", "=", "cursor", ";", "cachedType", "=", "type", ";", "cachedToken", "=", "token", ";", "}" ]
Cache the hints and the hint's context. @param {Array.<string>} hints - array of hints @param {{line:number, ch:number}} cursor - the location where the hints were created. @param {{property: boolean, showFunctionType:boolean, context: string, functionCallPos: {line:number, ch:number}}} type - type information about the hints @param {Object} token - CodeMirror token
[ "Cache", "the", "hints", "and", "the", "hint", "s", "context", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptCodeHints/main.js#L325-L330
2,010
adobe/brackets
src/extensions/default/JavaScriptCodeHints/main.js
getSessionHints
function getSessionHints(query, cursor, type, token, $deferredHints) { var hintResults = session.getHints(query, getStringMatcher()); if (hintResults.needGuesses) { var guessesResponse = ScopeManager.requestGuesses(session, session.editor.document); if (!$deferredHints) { $deferredHints = $.Deferred(); } guessesResponse.done(function () { if (hintsArePending($deferredHints)) { hintResults = session.getHints(query, getStringMatcher()); setCachedHintContext(hintResults.hints, cursor, type, token); var hintResponse = getHintResponse(cachedHints, query, type); $deferredHints.resolveWith(null, [hintResponse]); } }).fail(function () { if (hintsArePending($deferredHints)) { $deferredHints.reject(); } }); return $deferredHints; } else if (hintsArePending($deferredHints)) { setCachedHintContext(hintResults.hints, cursor, type, token); var hintResponse = getHintResponse(cachedHints, query, type); $deferredHints.resolveWith(null, [hintResponse]); return null; } else { setCachedHintContext(hintResults.hints, cursor, type, token); return getHintResponse(cachedHints, query, type); } }
javascript
function getSessionHints(query, cursor, type, token, $deferredHints) { var hintResults = session.getHints(query, getStringMatcher()); if (hintResults.needGuesses) { var guessesResponse = ScopeManager.requestGuesses(session, session.editor.document); if (!$deferredHints) { $deferredHints = $.Deferred(); } guessesResponse.done(function () { if (hintsArePending($deferredHints)) { hintResults = session.getHints(query, getStringMatcher()); setCachedHintContext(hintResults.hints, cursor, type, token); var hintResponse = getHintResponse(cachedHints, query, type); $deferredHints.resolveWith(null, [hintResponse]); } }).fail(function () { if (hintsArePending($deferredHints)) { $deferredHints.reject(); } }); return $deferredHints; } else if (hintsArePending($deferredHints)) { setCachedHintContext(hintResults.hints, cursor, type, token); var hintResponse = getHintResponse(cachedHints, query, type); $deferredHints.resolveWith(null, [hintResponse]); return null; } else { setCachedHintContext(hintResults.hints, cursor, type, token); return getHintResponse(cachedHints, query, type); } }
[ "function", "getSessionHints", "(", "query", ",", "cursor", ",", "type", ",", "token", ",", "$deferredHints", ")", "{", "var", "hintResults", "=", "session", ".", "getHints", "(", "query", ",", "getStringMatcher", "(", ")", ")", ";", "if", "(", "hintResults", ".", "needGuesses", ")", "{", "var", "guessesResponse", "=", "ScopeManager", ".", "requestGuesses", "(", "session", ",", "session", ".", "editor", ".", "document", ")", ";", "if", "(", "!", "$deferredHints", ")", "{", "$deferredHints", "=", "$", ".", "Deferred", "(", ")", ";", "}", "guessesResponse", ".", "done", "(", "function", "(", ")", "{", "if", "(", "hintsArePending", "(", "$deferredHints", ")", ")", "{", "hintResults", "=", "session", ".", "getHints", "(", "query", ",", "getStringMatcher", "(", ")", ")", ";", "setCachedHintContext", "(", "hintResults", ".", "hints", ",", "cursor", ",", "type", ",", "token", ")", ";", "var", "hintResponse", "=", "getHintResponse", "(", "cachedHints", ",", "query", ",", "type", ")", ";", "$deferredHints", ".", "resolveWith", "(", "null", ",", "[", "hintResponse", "]", ")", ";", "}", "}", ")", ".", "fail", "(", "function", "(", ")", "{", "if", "(", "hintsArePending", "(", "$deferredHints", ")", ")", "{", "$deferredHints", ".", "reject", "(", ")", ";", "}", "}", ")", ";", "return", "$deferredHints", ";", "}", "else", "if", "(", "hintsArePending", "(", "$deferredHints", ")", ")", "{", "setCachedHintContext", "(", "hintResults", ".", "hints", ",", "cursor", ",", "type", ",", "token", ")", ";", "var", "hintResponse", "=", "getHintResponse", "(", "cachedHints", ",", "query", ",", "type", ")", ";", "$deferredHints", ".", "resolveWith", "(", "null", ",", "[", "hintResponse", "]", ")", ";", "return", "null", ";", "}", "else", "{", "setCachedHintContext", "(", "hintResults", ".", "hints", ",", "cursor", ",", "type", ",", "token", ")", ";", "return", "getHintResponse", "(", "cachedHints", ",", "query", ",", "type", ")", ";", "}", "}" ]
Common code to get the session hints. Will get guesses if there were no completions for the query. @param {string} query - user text to search hints with @param {{line:number, ch:number}} cursor - the location where the hints were created. @param {{property: boolean, showFunctionType:boolean, context: string, functionCallPos: {line:number, ch:number}}} type - type information about the hints @param {Object} token - CodeMirror token @param {jQuery.Deferred=} $deferredHints - existing Deferred we need to resolve (optional). If not supplied a new Deferred will be created if needed. @return {Object + jQuery.Deferred} - hint response (immediate or deferred) as defined by the CodeHintManager API
[ "Common", "code", "to", "get", "the", "session", "hints", ".", "Will", "get", "guesses", "if", "there", "were", "no", "completions", "for", "the", "query", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptCodeHints/main.js#L442-L476
2,011
adobe/brackets
src/extensions/default/JavaScriptCodeHints/main.js
requestJumpToDef
function requestJumpToDef(session, offset) { var response = ScopeManager.requestJumptoDef(session, session.editor.document, offset); if (response.hasOwnProperty("promise")) { response.promise.done(handleJumpResponse).fail(function () { result.reject(); }); } }
javascript
function requestJumpToDef(session, offset) { var response = ScopeManager.requestJumptoDef(session, session.editor.document, offset); if (response.hasOwnProperty("promise")) { response.promise.done(handleJumpResponse).fail(function () { result.reject(); }); } }
[ "function", "requestJumpToDef", "(", "session", ",", "offset", ")", "{", "var", "response", "=", "ScopeManager", ".", "requestJumptoDef", "(", "session", ",", "session", ".", "editor", ".", "document", ",", "offset", ")", ";", "if", "(", "response", ".", "hasOwnProperty", "(", "\"promise\"", ")", ")", "{", "response", ".", "promise", ".", "done", "(", "handleJumpResponse", ")", ".", "fail", "(", "function", "(", ")", "{", "result", ".", "reject", "(", ")", ";", "}", ")", ";", "}", "}" ]
Make a jump-to-def request based on the session and offset passed in. @param {Session} session - the session @param {number} offset - the offset of where to jump from
[ "Make", "a", "jump", "-", "to", "-", "def", "request", "based", "on", "the", "session", "and", "offset", "passed", "in", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptCodeHints/main.js#L753-L761
2,012
adobe/brackets
src/extensions/default/JavaScriptCodeHints/main.js
setJumpSelection
function setJumpSelection(start, end, isFunction) { /** * helper function to decide if the tokens on the RHS of an assignment * look like an identifier, or member expr. */ function validIdOrProp(token) { if (!token) { return false; } if (token.string === ".") { return true; } var type = token.type; if (type === "variable-2" || type === "variable" || type === "property") { return true; } return false; } var madeNewRequest = false; if (isFunction) { // When jumping to function defs, follow the chain back // to get to the original function def var cursor = {line: end.line, ch: end.ch}, prev = session._getPreviousToken(cursor), next, offset; // see if the selection is preceded by a '.', indicating we're in a member expr if (prev.string === ".") { cursor = {line: end.line, ch: end.ch}; next = session.getNextToken(cursor, true); // check if the next token indicates an assignment if (next && next.string === "=") { next = session.getNextToken(cursor, true); // find the last token of the identifier, or member expr while (validIdOrProp(next)) { offset = session.getOffsetFromCursor({line: cursor.line, ch: next.end}); next = session.getNextToken(cursor, false); } if (offset) { // trigger another jump to def based on the offset of the RHS requestJumpToDef(session, offset); madeNewRequest = true; } } } } // We didn't make a new jump-to-def request, so we can resolve the promise // and set the selection if (!madeNewRequest) { // set the selection session.editor.setSelection(start, end, true); result.resolve(true); } }
javascript
function setJumpSelection(start, end, isFunction) { /** * helper function to decide if the tokens on the RHS of an assignment * look like an identifier, or member expr. */ function validIdOrProp(token) { if (!token) { return false; } if (token.string === ".") { return true; } var type = token.type; if (type === "variable-2" || type === "variable" || type === "property") { return true; } return false; } var madeNewRequest = false; if (isFunction) { // When jumping to function defs, follow the chain back // to get to the original function def var cursor = {line: end.line, ch: end.ch}, prev = session._getPreviousToken(cursor), next, offset; // see if the selection is preceded by a '.', indicating we're in a member expr if (prev.string === ".") { cursor = {line: end.line, ch: end.ch}; next = session.getNextToken(cursor, true); // check if the next token indicates an assignment if (next && next.string === "=") { next = session.getNextToken(cursor, true); // find the last token of the identifier, or member expr while (validIdOrProp(next)) { offset = session.getOffsetFromCursor({line: cursor.line, ch: next.end}); next = session.getNextToken(cursor, false); } if (offset) { // trigger another jump to def based on the offset of the RHS requestJumpToDef(session, offset); madeNewRequest = true; } } } } // We didn't make a new jump-to-def request, so we can resolve the promise // and set the selection if (!madeNewRequest) { // set the selection session.editor.setSelection(start, end, true); result.resolve(true); } }
[ "function", "setJumpSelection", "(", "start", ",", "end", ",", "isFunction", ")", "{", "/**\n * helper function to decide if the tokens on the RHS of an assignment\n * look like an identifier, or member expr.\n */", "function", "validIdOrProp", "(", "token", ")", "{", "if", "(", "!", "token", ")", "{", "return", "false", ";", "}", "if", "(", "token", ".", "string", "===", "\".\"", ")", "{", "return", "true", ";", "}", "var", "type", "=", "token", ".", "type", ";", "if", "(", "type", "===", "\"variable-2\"", "||", "type", "===", "\"variable\"", "||", "type", "===", "\"property\"", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}", "var", "madeNewRequest", "=", "false", ";", "if", "(", "isFunction", ")", "{", "// When jumping to function defs, follow the chain back", "// to get to the original function def", "var", "cursor", "=", "{", "line", ":", "end", ".", "line", ",", "ch", ":", "end", ".", "ch", "}", ",", "prev", "=", "session", ".", "_getPreviousToken", "(", "cursor", ")", ",", "next", ",", "offset", ";", "// see if the selection is preceded by a '.', indicating we're in a member expr", "if", "(", "prev", ".", "string", "===", "\".\"", ")", "{", "cursor", "=", "{", "line", ":", "end", ".", "line", ",", "ch", ":", "end", ".", "ch", "}", ";", "next", "=", "session", ".", "getNextToken", "(", "cursor", ",", "true", ")", ";", "// check if the next token indicates an assignment", "if", "(", "next", "&&", "next", ".", "string", "===", "\"=\"", ")", "{", "next", "=", "session", ".", "getNextToken", "(", "cursor", ",", "true", ")", ";", "// find the last token of the identifier, or member expr", "while", "(", "validIdOrProp", "(", "next", ")", ")", "{", "offset", "=", "session", ".", "getOffsetFromCursor", "(", "{", "line", ":", "cursor", ".", "line", ",", "ch", ":", "next", ".", "end", "}", ")", ";", "next", "=", "session", ".", "getNextToken", "(", "cursor", ",", "false", ")", ";", "}", "if", "(", "offset", ")", "{", "// trigger another jump to def based on the offset of the RHS", "requestJumpToDef", "(", "session", ",", "offset", ")", ";", "madeNewRequest", "=", "true", ";", "}", "}", "}", "}", "// We didn't make a new jump-to-def request, so we can resolve the promise", "// and set the selection", "if", "(", "!", "madeNewRequest", ")", "{", "// set the selection", "session", ".", "editor", ".", "setSelection", "(", "start", ",", "end", ",", "true", ")", ";", "result", ".", "resolve", "(", "true", ")", ";", "}", "}" ]
Sets the selection to move the cursor to the result position. Assumes that the editor has already changed files, if necessary. Additionally, this will check to see if the selection looks like an assignment to a member expression - if it is, and the type is a function, then we will attempt to jump to the RHS of the expression. 'exports.foo = foo' if the selection is 'foo' in 'exports.foo', then we will attempt to jump to def on the rhs of the assignment. @param {number} start - the start of the selection @param {number} end - the end of the selection @param {boolean} isFunction - true if we are jumping to the source of a function def
[ "Sets", "the", "selection", "to", "move", "the", "cursor", "to", "the", "result", "position", ".", "Assumes", "that", "the", "editor", "has", "already", "changed", "files", "if", "necessary", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptCodeHints/main.js#L781-L839
2,013
adobe/brackets
src/extensions/default/JavaScriptCodeHints/main.js
validIdOrProp
function validIdOrProp(token) { if (!token) { return false; } if (token.string === ".") { return true; } var type = token.type; if (type === "variable-2" || type === "variable" || type === "property") { return true; } return false; }
javascript
function validIdOrProp(token) { if (!token) { return false; } if (token.string === ".") { return true; } var type = token.type; if (type === "variable-2" || type === "variable" || type === "property") { return true; } return false; }
[ "function", "validIdOrProp", "(", "token", ")", "{", "if", "(", "!", "token", ")", "{", "return", "false", ";", "}", "if", "(", "token", ".", "string", "===", "\".\"", ")", "{", "return", "true", ";", "}", "var", "type", "=", "token", ".", "type", ";", "if", "(", "type", "===", "\"variable-2\"", "||", "type", "===", "\"variable\"", "||", "type", "===", "\"property\"", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
helper function to decide if the tokens on the RHS of an assignment look like an identifier, or member expr.
[ "helper", "function", "to", "decide", "if", "the", "tokens", "on", "the", "RHS", "of", "an", "assignment", "look", "like", "an", "identifier", "or", "member", "expr", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptCodeHints/main.js#L787-L800
2,014
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
_urlWithoutQueryString
function _urlWithoutQueryString(url) { var index = url.search(/[#\?]/); if (index >= 0) { url = url.substr(0, index); } return url; }
javascript
function _urlWithoutQueryString(url) { var index = url.search(/[#\?]/); if (index >= 0) { url = url.substr(0, index); } return url; }
[ "function", "_urlWithoutQueryString", "(", "url", ")", "{", "var", "index", "=", "url", ".", "search", "(", "/", "[#\\?]", "/", ")", ";", "if", "(", "index", ">=", "0", ")", "{", "url", "=", "url", ".", "substr", "(", "0", ",", "index", ")", ";", "}", "return", "url", ";", "}" ]
Return the URL without the query string @param {string} URL
[ "Return", "the", "URL", "without", "the", "query", "string" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L47-L53
2,015
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
_makeHTMLTarget
function _makeHTMLTarget(targets, node) { if (node.location) { var url = DOMAgent.url; var location = node.location; if (node.canHaveChildren()) { location += node.length; } url += ":" + location; var name = "&lt;" + node.name + "&gt;"; var file = _fileFromURL(url); targets.push({"type": "html", "url": url, "name": name, "file": file}); } }
javascript
function _makeHTMLTarget(targets, node) { if (node.location) { var url = DOMAgent.url; var location = node.location; if (node.canHaveChildren()) { location += node.length; } url += ":" + location; var name = "&lt;" + node.name + "&gt;"; var file = _fileFromURL(url); targets.push({"type": "html", "url": url, "name": name, "file": file}); } }
[ "function", "_makeHTMLTarget", "(", "targets", ",", "node", ")", "{", "if", "(", "node", ".", "location", ")", "{", "var", "url", "=", "DOMAgent", ".", "url", ";", "var", "location", "=", "node", ".", "location", ";", "if", "(", "node", ".", "canHaveChildren", "(", ")", ")", "{", "location", "+=", "node", ".", "length", ";", "}", "url", "+=", "\":\"", "+", "location", ";", "var", "name", "=", "\"&lt;\"", "+", "node", ".", "name", "+", "\"&gt;\"", ";", "var", "file", "=", "_fileFromURL", "(", "url", ")", ";", "targets", ".", "push", "(", "{", "\"type\"", ":", "\"html\"", ",", "\"url\"", ":", "url", ",", "\"name\"", ":", "name", ",", "\"file\"", ":", "file", "}", ")", ";", "}", "}" ]
Make the given node a target for goto @param [] targets array @param {DOMNode} node
[ "Make", "the", "given", "node", "a", "target", "for", "goto" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L67-L79
2,016
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
_makeCSSTarget
function _makeCSSTarget(targets, rule) { if (rule.sourceURL) { var url = rule.sourceURL; url += ":" + rule.style.range.start; var name = rule.selectorList.text; var file = _fileFromURL(url); targets.push({"type": "css", "url": url, "name": name, "file": file}); } }
javascript
function _makeCSSTarget(targets, rule) { if (rule.sourceURL) { var url = rule.sourceURL; url += ":" + rule.style.range.start; var name = rule.selectorList.text; var file = _fileFromURL(url); targets.push({"type": "css", "url": url, "name": name, "file": file}); } }
[ "function", "_makeCSSTarget", "(", "targets", ",", "rule", ")", "{", "if", "(", "rule", ".", "sourceURL", ")", "{", "var", "url", "=", "rule", ".", "sourceURL", ";", "url", "+=", "\":\"", "+", "rule", ".", "style", ".", "range", ".", "start", ";", "var", "name", "=", "rule", ".", "selectorList", ".", "text", ";", "var", "file", "=", "_fileFromURL", "(", "url", ")", ";", "targets", ".", "push", "(", "{", "\"type\"", ":", "\"css\"", ",", "\"url\"", ":", "url", ",", "\"name\"", ":", "name", ",", "\"file\"", ":", "file", "}", ")", ";", "}", "}" ]
Make the given css rule a target for goto @param [] targets array @param {CSS.Rule} node
[ "Make", "the", "given", "css", "rule", "a", "target", "for", "goto" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L85-L93
2,017
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
_makeJSTarget
function _makeJSTarget(targets, callFrame) { var script = ScriptAgent.scriptWithId(callFrame.location.scriptId); if (script && script.url) { var url = script.url; url += ":" + callFrame.location.lineNumber + "," + callFrame.location.columnNumber; var name = callFrame.functionName; if (name === "") { name = "anonymous function"; } var file = _fileFromURL(url); targets.push({"type": "js", "url": url, "name": name, "file": file}); } }
javascript
function _makeJSTarget(targets, callFrame) { var script = ScriptAgent.scriptWithId(callFrame.location.scriptId); if (script && script.url) { var url = script.url; url += ":" + callFrame.location.lineNumber + "," + callFrame.location.columnNumber; var name = callFrame.functionName; if (name === "") { name = "anonymous function"; } var file = _fileFromURL(url); targets.push({"type": "js", "url": url, "name": name, "file": file}); } }
[ "function", "_makeJSTarget", "(", "targets", ",", "callFrame", ")", "{", "var", "script", "=", "ScriptAgent", ".", "scriptWithId", "(", "callFrame", ".", "location", ".", "scriptId", ")", ";", "if", "(", "script", "&&", "script", ".", "url", ")", "{", "var", "url", "=", "script", ".", "url", ";", "url", "+=", "\":\"", "+", "callFrame", ".", "location", ".", "lineNumber", "+", "\",\"", "+", "callFrame", ".", "location", ".", "columnNumber", ";", "var", "name", "=", "callFrame", ".", "functionName", ";", "if", "(", "name", "===", "\"\"", ")", "{", "name", "=", "\"anonymous function\"", ";", "}", "var", "file", "=", "_fileFromURL", "(", "url", ")", ";", "targets", ".", "push", "(", "{", "\"type\"", ":", "\"js\"", ",", "\"url\"", ":", "url", ",", "\"name\"", ":", "name", ",", "\"file\"", ":", "file", "}", ")", ";", "}", "}" ]
Make the given javascript callFrame the target for goto @param [] targets array @param {Debugger.CallFrame} node
[ "Make", "the", "given", "javascript", "callFrame", "the", "target", "for", "goto" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L99-L111
2,018
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
_onRemoteShowGoto
function _onRemoteShowGoto(event, res) { // res = {nodeId, name, value} var node = DOMAgent.nodeWithId(res.nodeId); // get all css rules that apply to the given node Inspector.CSS.getMatchedStylesForNode(node.nodeId, function onMatchedStyles(res) { var i, targets = []; _makeHTMLTarget(targets, node); for (i in node.trace) { _makeJSTarget(targets, node.trace[i]); } for (i in node.events) { var trace = node.events[i]; _makeJSTarget(targets, trace.callFrames[0]); } for (i in res.matchedCSSRules.reverse()) { _makeCSSTarget(targets, res.matchedCSSRules[i].rule); } RemoteAgent.call("showGoto", targets); }); }
javascript
function _onRemoteShowGoto(event, res) { // res = {nodeId, name, value} var node = DOMAgent.nodeWithId(res.nodeId); // get all css rules that apply to the given node Inspector.CSS.getMatchedStylesForNode(node.nodeId, function onMatchedStyles(res) { var i, targets = []; _makeHTMLTarget(targets, node); for (i in node.trace) { _makeJSTarget(targets, node.trace[i]); } for (i in node.events) { var trace = node.events[i]; _makeJSTarget(targets, trace.callFrames[0]); } for (i in res.matchedCSSRules.reverse()) { _makeCSSTarget(targets, res.matchedCSSRules[i].rule); } RemoteAgent.call("showGoto", targets); }); }
[ "function", "_onRemoteShowGoto", "(", "event", ",", "res", ")", "{", "// res = {nodeId, name, value}", "var", "node", "=", "DOMAgent", ".", "nodeWithId", "(", "res", ".", "nodeId", ")", ";", "// get all css rules that apply to the given node", "Inspector", ".", "CSS", ".", "getMatchedStylesForNode", "(", "node", ".", "nodeId", ",", "function", "onMatchedStyles", "(", "res", ")", "{", "var", "i", ",", "targets", "=", "[", "]", ";", "_makeHTMLTarget", "(", "targets", ",", "node", ")", ";", "for", "(", "i", "in", "node", ".", "trace", ")", "{", "_makeJSTarget", "(", "targets", ",", "node", ".", "trace", "[", "i", "]", ")", ";", "}", "for", "(", "i", "in", "node", ".", "events", ")", "{", "var", "trace", "=", "node", ".", "events", "[", "i", "]", ";", "_makeJSTarget", "(", "targets", ",", "trace", ".", "callFrames", "[", "0", "]", ")", ";", "}", "for", "(", "i", "in", "res", ".", "matchedCSSRules", ".", "reverse", "(", ")", ")", "{", "_makeCSSTarget", "(", "targets", ",", "res", ".", "matchedCSSRules", "[", "i", "]", ".", "rule", ")", ";", "}", "RemoteAgent", ".", "call", "(", "\"showGoto\"", ",", "targets", ")", ";", "}", ")", ";", "}" ]
Gather options where to go to from the given source node
[ "Gather", "options", "where", "to", "go", "to", "from", "the", "given", "source", "node" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L114-L134
2,019
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
openLocation
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
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); } }
[ "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", ")", ";", "}", "}" ]
Point the master editor to the given location @param {integer} location in file
[ "Point", "the", "master", "editor", "to", "the", "given", "location" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L139-L154
2,020
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
open
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
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(); }
[ "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", "(", ")", ";", "}" ]
Open the editor at the given url and editor location @param {string} url @param {integer} optional location in file
[ "Open", "the", "editor", "at", "the", "given", "url", "and", "editor", "location" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L160-L183
2,021
adobe/brackets
src/LiveDevelopment/Agents/GotoAgent.js
_onRemoteGoto
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
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); }
[ "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", ")", ";", "}" ]
Go to the given source node
[ "Go", "to", "the", "given", "source", "node" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/GotoAgent.js#L186-L200
2,022
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
_removeQuotes
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
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; }
[ "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", ";", "}" ]
Remove quotes from the string and adjust escaped quotes @param {string} source string
[ "Remove", "quotes", "from", "the", "string", "and", "adjust", "escaped", "quotes" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L50-L57
2,023
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
_find
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
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; }
[ "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", ";", "}" ]
Find the next match using several constraints @param {string} source string @param {string} or [{regex}, {length}] the match definition @param {integer} ignore characters before this offset @param {boolean} watch for quotes @param [{string},{string}] watch for comments
[ "Find", "the", "next", "match", "using", "several", "constraints" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L66-L96
2,024
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
_findEach
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
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; } }
[ "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", ";", "}", "}" ]
Callback iterator using `_find`
[ "Callback", "iterator", "using", "_find" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L99-L110
2,025
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
_findTag
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
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}; }
[ "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", "}", ";", "}" ]
Find the next tag @param {string} source string @param {integer} ignore characters before this offset
[ "Find", "the", "next", "tag" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L116-L142
2,026
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
_extractAttributes
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
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; }
[ "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", ";", "}" ]
Extract tag attributes from the given source of a single tag @param {string} source content
[ "Extract", "tag", "attributes", "from", "the", "given", "source", "of", "a", "single", "tag" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L147-L178
2,027
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
extractPayload
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
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; }
[ "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", ";", "}" ]
Extract the node payload @param {string} source content
[ "Extract", "the", "node", "payload" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L183-L221
2,028
adobe/brackets
src/LiveDevelopment/Agents/DOMHelpers.js
eachNode
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
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; } }
[ "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", ";", "}", "}" ]
Split the source string into payloads representing individual nodes @param {string} source @param {function(payload)} callback split a string into individual node contents
[ "Split", "the", "source", "string", "into", "payloads", "representing", "individual", "nodes" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/DOMHelpers.js#L228-L262
2,029
adobe/brackets
src/document/Document.js
Document
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
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 = []; }
[ "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", "=", "[", "]", ";", "}" ]
Model for the contents of a single file and its current modification state. See DocumentManager documentation for important usage notes. Document dispatches these events: __change__ -- When the text of the editor changes (including due to undo/redo). Passes ({Document}, {ChangeList}), where ChangeList is an array of change record objects. Each change record looks like: { from: start of change, expressed as {line: <line number>, ch: <character offset>}, to: end of change, expressed as {line: <line number>, ch: <chracter offset>}, text: array of lines of text to replace existing text } The line and ch offsets are both 0-based. The ch offset in "from" is inclusive, but the ch offset in "to" is exclusive. For example, an insertion of new content (without replacing existing content) is expressed by a range where from and to are the same. If "from" and "to" are undefined, then this is a replacement of the entire text content. IMPORTANT: If you listen for the "change" event, you MUST also addRef() the document (and releaseRef() it whenever you stop listening). You should also listen to the "deleted" event. __deleted__ -- When the file for this document has been deleted. All views onto the document should be closed. The document will no longer be editable or dispatch "change" events. __languageChanged__ -- When the value of getLanguage() has changed. 2nd argument is the old value, 3rd argument is the new value. @constructor @param {!File} file Need not lie within the project. @param {!Date} initialTimestamp File's timestamp when we read it off disk. @param {!string} rawText Text content of the file.
[ "Model", "for", "the", "contents", "of", "a", "single", "file", "and", "its", "current", "modification", "state", ".", "See", "DocumentManager", "documentation", "for", "important", "usage", "notes", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/Document.js#L74-L81
2,030
adobe/brackets
src/LiveDevelopment/Agents/RemoteAgent.js
call
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
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); }
[ "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", ")", ";", "}" ]
Call a remote function The parameters are passed on to the remote functions. Nodes are resolved and sent as objectIds. @param {string} function name
[ "Call", "a", "remote", "function", "The", "parameters", "are", "passed", "on", "to", "the", "remote", "functions", ".", "Nodes", "are", "resolved", "and", "sent", "as", "objectIds", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/Agents/RemoteAgent.js#L98-L106
2,031
adobe/brackets
src/extensions/default/InlineColorEditor/InlineColorEditor.js
InlineColorEditor
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
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); }
[ "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", ")", ";", "}" ]
Inline widget containing a ColorEditor control @param {!string} color Initially selected color @param {!CodeMirror.TextMarker} marker
[ "Inline", "widget", "containing", "a", "ColorEditor", "control" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/InlineColorEditor/InlineColorEditor.js#L43-L54
2,032
adobe/brackets
src/extensions/default/InlineColorEditor/InlineColorEditor.js
_colorSort
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
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; } }
[ "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", ";", "}", "}" ]
Comparator to sort by which colors are used the most
[ "Comparator", "to", "sort", "by", "which", "colors", "are", "used", "the", "most" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/InlineColorEditor/InlineColorEditor.js#L210-L220
2,033
adobe/brackets
src/utils/DragAndDrop.js
isValidDrop
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
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; }
[ "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", ";", "}" ]
Returns true if the drag and drop items contains valid drop objects. @param {Array.<DataTransferItem>} items Array of items being dragged @return {boolean} True if one or more items can be dropped.
[ "Returns", "true", "if", "the", "drag", "and", "drop", "items", "contains", "valid", "drop", "objects", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/DragAndDrop.js#L44-L63
2,034
adobe/brackets
src/utils/DragAndDrop.js
stopURIListPropagation
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
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; } }); } }
[ "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", ";", "}", "}", ")", ";", "}", "}" ]
Determines if the event contains a type list that has a URI-list. If it does and contains an empty file list, then what is being dropped is a URL. If that is true then we stop the event propagation and default behavior to save Brackets editor from the browser taking over. @param {Array.<File>} files Array of File objects from the event datastructure. URLs are the only drop item that would contain a URI-list. @param {event} event The event datastucture containing datatransfer information about the drag/drop event. Contains a type list which may or may not hold a URI-list depending on what was dragged/dropped. Interested if it does.
[ "Determines", "if", "the", "event", "contains", "a", "type", "list", "that", "has", "a", "URI", "-", "list", ".", "If", "it", "does", "and", "contains", "an", "empty", "file", "list", "then", "what", "is", "being", "dropped", "is", "a", "URL", ".", "If", "that", "is", "true", "then", "we", "stop", "the", "event", "propagation", "and", "default", "behavior", "to", "save", "Brackets", "editor", "from", "the", "browser", "taking", "over", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/DragAndDrop.js#L72-L88
2,035
adobe/brackets
src/utils/DragAndDrop.js
openDroppedFiles
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
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 ); } }); }
[ "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", ")", ";", "}", "}", ")", ";", "}" ]
Open dropped files @param {Array.<string>} files Array of files dropped on the application. @return {Promise} Promise that is resolved if all files are opened, or rejected if there was an error.
[ "Open", "dropped", "files" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/DragAndDrop.js#L96-L171
2,036
adobe/brackets
src/search/ScrollTrackMarkers.js
_calcScaling
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
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; } }
[ "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", ";", "}", "}" ]
Measure scrollbar track
[ "Measure", "scrollbar", "track" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/search/ScrollTrackMarkers.js#L109-L123
2,037
adobe/brackets
src/search/ScrollTrackMarkers.js
_renderMarks
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
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)); }
[ "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", ")", ")", ";", "}" ]
Add all the given tickmarks to the DOM in a batch
[ "Add", "all", "the", "given", "tickmarks", "to", "the", "DOM", "in", "a", "batch" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/search/ScrollTrackMarkers.js#L126-L157
2,038
adobe/brackets
src/search/ScrollTrackMarkers.js
setVisible
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
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"); } }
[ "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\"", ")", ";", "}", "}" ]
Add or remove the tickmark track from the editor's UI
[ "Add", "or", "remove", "the", "tickmark", "track", "from", "the", "editor", "s", "UI" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/search/ScrollTrackMarkers.js#L173-L210
2,039
adobe/brackets
src/search/ScrollTrackMarkers.js
addTickmarks
function addTickmarks(curEditor, posArray) { console.assert(editor === curEditor); marks = marks.concat(posArray); _renderMarks(posArray); }
javascript
function addTickmarks(curEditor, posArray) { console.assert(editor === curEditor); marks = marks.concat(posArray); _renderMarks(posArray); }
[ "function", "addTickmarks", "(", "curEditor", ",", "posArray", ")", "{", "console", ".", "assert", "(", "editor", "===", "curEditor", ")", ";", "marks", "=", "marks", ".", "concat", "(", "posArray", ")", ";", "_renderMarks", "(", "posArray", ")", ";", "}" ]
Add tickmarks to the editor's tickmark track, if it's visible @param curEditor {!Editor} @param posArray {!Array.<{line:Number, ch:Number}>}
[ "Add", "tickmarks", "to", "the", "editor", "s", "tickmark", "track", "if", "it", "s", "visible" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/search/ScrollTrackMarkers.js#L217-L222
2,040
adobe/brackets
src/JSUtils/HintUtils.js
maybeIdentifier
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
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; }
[ "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", ";", "}" ]
Is the string key perhaps a valid JavaScript identifier? @param {string} key - string to test. @return {boolean} - could key be a valid identifier?
[ "Is", "the", "string", "key", "perhaps", "a", "valid", "JavaScript", "identifier?" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/JSUtils/HintUtils.js#L63-L75
2,041
adobe/brackets
src/project/FileTreeViewModel.js
_closeSubtree
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
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; }
[ "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", ";", "}" ]
Closes a subtree path, given by an object path. @param {Immutable.Map} directory Current directory @return {Immutable.Map} new directory
[ "Closes", "a", "subtree", "path", "given", "by", "an", "object", "path", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/project/FileTreeViewModel.js#L597-L613
2,042
adobe/brackets
src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js
getRefs
function getRefs(fileInfo, offset) { ScopeManager.postMessage({ type: MessageIds.TERN_REFS, fileInfo: fileInfo, offset: offset }); return ScopeManager.addPendingRequest(fileInfo.name, offset, MessageIds.TERN_REFS); }
javascript
function getRefs(fileInfo, offset) { ScopeManager.postMessage({ type: MessageIds.TERN_REFS, fileInfo: fileInfo, offset: offset }); return ScopeManager.addPendingRequest(fileInfo.name, offset, MessageIds.TERN_REFS); }
[ "function", "getRefs", "(", "fileInfo", ",", "offset", ")", "{", "ScopeManager", ".", "postMessage", "(", "{", "type", ":", "MessageIds", ".", "TERN_REFS", ",", "fileInfo", ":", "fileInfo", ",", "offset", ":", "offset", "}", ")", ";", "return", "ScopeManager", ".", "addPendingRequest", "(", "fileInfo", ".", "name", ",", "offset", ",", "MessageIds", ".", "TERN_REFS", ")", ";", "}" ]
Post message to tern node domain that will request tern server to find refs
[ "Post", "message", "to", "tern", "node", "domain", "that", "will", "request", "tern", "server", "to", "find", "refs" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js#L44-L52
2,043
adobe/brackets
src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js
requestFindRefs
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
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}; }
[ "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", "}", ";", "}" ]
Create info required to find reference
[ "Create", "info", "required", "to", "find", "reference" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js#L55-L69
2,044
adobe/brackets
src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js
handleFindRefs
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
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); }
[ "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", ")", ";", "}" ]
Check if references are in this file only If yes then select all references
[ "Check", "if", "references", "are", "in", "this", "file", "only", "If", "yes", "then", "select", "all", "references" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js#L123-L162
2,045
adobe/brackets
src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js
requestFindReferences
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
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(); }); } }
[ "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", "(", ")", ";", "}", ")", ";", "}", "}" ]
Make a find ref request. @param {Session} session - the session @param {number} offset - the offset of where to jump from
[ "Make", "a", "find", "ref", "request", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/JavaScriptRefactoring/RenameIdentifier.js#L169-L177
2,046
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
_classForDocument
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
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; }
[ "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", ";", "}" ]
Determine which document class should be used for a given document @param {Document} document
[ "Determine", "which", "document", "class", "should", "be", "used", "for", "a", "given", "document" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L224-L240
2,047
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
enableAgent
function enableAgent(name) { if (agents.hasOwnProperty(name) && !_enabledAgentNames.hasOwnProperty(name)) { _enabledAgentNames[name] = true; } }
javascript
function enableAgent(name) { if (agents.hasOwnProperty(name) && !_enabledAgentNames.hasOwnProperty(name)) { _enabledAgentNames[name] = true; } }
[ "function", "enableAgent", "(", "name", ")", "{", "if", "(", "agents", ".", "hasOwnProperty", "(", "name", ")", "&&", "!", "_enabledAgentNames", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "_enabledAgentNames", "[", "name", "]", "=", "true", ";", "}", "}" ]
Enable an agent. Takes effect next time a connection is made. Does not affect current live development sessions. @param {string} name of agent to enable
[ "Enable", "an", "agent", ".", "Takes", "effect", "next", "time", "a", "connection", "is", "made", ".", "Does", "not", "affect", "current", "live", "development", "sessions", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L444-L448
2,048
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
_onError
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
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); }
[ "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", ")", ";", "}" ]
Triggered by Inspector.error
[ "Triggered", "by", "Inspector", ".", "error" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L473-L497
2,049
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
loadAgents
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
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; }
[ "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", ";", "}" ]
Load the agents
[ "Load", "the", "agents" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L595-L657
2,050
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
onActiveEditorChange
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
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); } }
[ "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", ")", ";", "}", "}" ]
If the current editor is for a CSS preprocessor file, then add it to the style sheet so that we can track cursor positions in the editor to show live preview highlighting. For normal CSS we only do highlighting from files we know for sure are referenced by the current live preview document, but for preprocessors we just assume that any preprocessor file you edit is probably related to the live preview. @param {Event} event (unused) @param {Editor} current Current editor @param {Editor} previous Previous editor
[ "If", "the", "current", "editor", "is", "for", "a", "CSS", "preprocessor", "file", "then", "add", "it", "to", "the", "style", "sheet", "so", "that", "we", "can", "track", "cursor", "positions", "in", "the", "editor", "to", "show", "live", "preview", "highlighting", ".", "For", "normal", "CSS", "we", "only", "do", "highlighting", "from", "files", "we", "know", "for", "sure", "are", "referenced", "by", "the", "current", "live", "preview", "document", "but", "for", "preprocessors", "we", "just", "assume", "that", "any", "preprocessor", "file", "you", "edit", "is", "probably", "related", "to", "the", "live", "preview", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L783-L797
2,051
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
reconnect
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
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(); }
[ "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", "(", ")", ";", "}" ]
Unload and reload agents @return {jQuery.Promise} Resolves once the agents are loaded
[ "Unload", "and", "reload", "agents" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L972-L989
2,052
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
_onConnect
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
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); }
[ "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", ")", ";", "}" ]
Triggered by Inspector.connect
[ "Triggered", "by", "Inspector", ".", "connect" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L1101-L1119
2,053
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
_doLaunchAfterServerReady
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
helper function that actually does the launch once we are sure we have a doc and the server for that doc is up and running.
[ "helper", "function", "that", "actually", "does", "the", "launch", "once", "we", "are", "sure", "we", "have", "a", "doc", "and", "the", "server", "for", "that", "doc", "is", "up", "and", "running", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L1244-L1269
2,054
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
open
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
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(); }
[ "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", "(", ")", ";", "}" ]
Open the Connection and go live @param {!boolean} restart true if relaunching and _openDeferred already exists @return {jQuery.Promise} Resolves once live preview is open
[ "Open", "the", "Connection", "and", "go", "live" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L1335-L1398
2,055
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
_onDocumentSaved
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
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(); } }
[ "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", "(", ")", ";", "}", "}" ]
Triggered by a documentSaved event from DocumentManager. @param {$.Event} event @param {Document} doc
[ "Triggered", "by", "a", "documentSaved", "event", "from", "DocumentManager", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L1468-L1488
2,056
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
_onDirtyFlagChange
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
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); } }
[ "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", ")", ";", "}", "}" ]
Triggered by a change in dirty flag from the DocumentManager
[ "Triggered", "by", "a", "change", "in", "dirty", "flag", "from", "the", "DocumentManager" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L1491-L1497
2,057
adobe/brackets
src/LiveDevelopment/LiveDevelopment.js
init
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
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); }
[ "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", ")", ";", "}" ]
Initialize the LiveDevelopment Session
[ "Initialize", "the", "LiveDevelopment", "Session" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L1500-L1520
2,058
adobe/brackets
src/extensions/default/HealthData/main.js
addCommand
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
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); }
[ "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", ")", ";", "}" ]
Register the command and add the menu item for the Health Data Statistics
[ "Register", "the", "command", "and", "add", "the", "menu", "item", "for", "the", "Health", "Data", "Statistics" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/HealthData/main.js#L48-L53
2,059
adobe/brackets
src/editor/EditorManager.js
getCurrentFullEditor
function getCurrentFullEditor() { var currentPath = MainViewManager.getCurrentlyViewedPath(MainViewManager.ACTIVE_PANE), doc = currentPath && DocumentManager.getOpenDocumentForPath(currentPath); return doc && doc._masterEditor; }
javascript
function getCurrentFullEditor() { var currentPath = MainViewManager.getCurrentlyViewedPath(MainViewManager.ACTIVE_PANE), doc = currentPath && DocumentManager.getOpenDocumentForPath(currentPath); return doc && doc._masterEditor; }
[ "function", "getCurrentFullEditor", "(", ")", "{", "var", "currentPath", "=", "MainViewManager", ".", "getCurrentlyViewedPath", "(", "MainViewManager", ".", "ACTIVE_PANE", ")", ",", "doc", "=", "currentPath", "&&", "DocumentManager", ".", "getOpenDocumentForPath", "(", "currentPath", ")", ";", "return", "doc", "&&", "doc", ".", "_masterEditor", ";", "}" ]
Retrieves the visible full-size Editor for the currently opened file in the ACTIVE_PANE @return {?Editor} editor of the current view or null
[ "Retrieves", "the", "visible", "full", "-", "size", "Editor", "for", "the", "currently", "opened", "file", "in", "the", "ACTIVE_PANE" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L107-L111
2,060
adobe/brackets
src/editor/EditorManager.js
_restoreEditorViewState
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
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); } }
[ "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", ")", ";", "}", "}" ]
Updates _viewStateCache from the given editor's actual current state @param {!Editor} editor - editor restore cached data @private
[ "Updates", "_viewStateCache", "from", "the", "given", "editor", "s", "actual", "current", "state" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L129-L135
2,061
adobe/brackets
src/editor/EditorManager.js
_notifyActiveEditorChanged
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
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); }
[ "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", ")", ";", "}" ]
Editor focus handler to change the currently active editor @private @param {?Editor} current - the editor that will be the active editor
[ "Editor", "focus", "handler", "to", "change", "the", "currently", "active", "editor" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L143-L153
2,062
adobe/brackets
src/editor/EditorManager.js
_createEditorForDocument
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
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; }
[ "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", ";", "}" ]
Creates a new Editor bound to the given Document. The editor is appended to the given container as a visible child. @private @param {!Document} doc Document for the Editor's content @param {!boolean} makeMasterEditor If true, the Editor will set itself as the private "master" Editor for the Document. If false, the Editor will attach to the Document as a "slave." @param {!jQueryObject} container Container to add the editor to. @param {{startLine: number, endLine: number}=} range If specified, range of lines within the document to display in this editor. Inclusive. @param {!Object} editorOptions If specified, contains editor options that can be passed to CodeMirror @return {Editor} the newly created editor.
[ "Creates", "a", "new", "Editor", "bound", "to", "the", "given", "Document", ".", "The", "editor", "is", "appended", "to", "the", "given", "container", "as", "a", "visible", "child", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L185-L199
2,063
adobe/brackets
src/editor/EditorManager.js
_toggleInlineWidget
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
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(); }
[ "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", "(", ")", ";", "}" ]
Closes any focused inline widget. Else, asynchronously asks providers to create one. @param {Array.<{priority:number, provider:function(...)}>} providers prioritized list of providers @param {string=} errorMsg Default message to display if no providers return non-null @return {!Promise} A promise resolved with true if an inline widget is opened or false when closed. Rejected if there is neither an existing widget to close nor a provider willing to create a widget (or if no editor is open).
[ "Closes", "any", "focused", "inline", "widget", ".", "Else", "asynchronously", "asks", "providers", "to", "create", "one", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L282-L312
2,064
adobe/brackets
src/editor/EditorManager.js
registerInlineEditProvider
function registerInlineEditProvider(provider, priority) { if (priority === undefined) { priority = 0; } _insertProviderSorted(_inlineEditProviders, provider, priority); }
javascript
function registerInlineEditProvider(provider, priority) { if (priority === undefined) { priority = 0; } _insertProviderSorted(_inlineEditProviders, provider, priority); }
[ "function", "registerInlineEditProvider", "(", "provider", ",", "priority", ")", "{", "if", "(", "priority", "===", "undefined", ")", "{", "priority", "=", "0", ";", "}", "_insertProviderSorted", "(", "_inlineEditProviders", ",", "provider", ",", "priority", ")", ";", "}" ]
Registers a new inline editor provider. When Quick Edit is invoked each registered provider is asked if it wants to provide an inline editor given the current editor and cursor location. An optional priority parameter is used to give providers with higher priority an opportunity to provide an inline editor before providers with lower priority. @param {function(!Editor, !{line:number, ch:number}):?($.Promise|string)} provider @param {number=} priority The provider returns a promise that will be resolved with an InlineWidget, or returns a string indicating why the provider cannot respond to this case (or returns null to indicate no reason).
[ "Registers", "a", "new", "inline", "editor", "provider", ".", "When", "Quick", "Edit", "is", "invoked", "each", "registered", "provider", "is", "asked", "if", "it", "wants", "to", "provide", "an", "inline", "editor", "given", "the", "current", "editor", "and", "cursor", "location", ".", "An", "optional", "priority", "parameter", "is", "used", "to", "give", "providers", "with", "higher", "priority", "an", "opportunity", "to", "provide", "an", "inline", "editor", "before", "providers", "with", "lower", "priority", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L392-L397
2,065
adobe/brackets
src/editor/EditorManager.js
registerInlineDocsProvider
function registerInlineDocsProvider(provider, priority) { if (priority === undefined) { priority = 0; } _insertProviderSorted(_inlineDocsProviders, provider, priority); }
javascript
function registerInlineDocsProvider(provider, priority) { if (priority === undefined) { priority = 0; } _insertProviderSorted(_inlineDocsProviders, provider, priority); }
[ "function", "registerInlineDocsProvider", "(", "provider", ",", "priority", ")", "{", "if", "(", "priority", "===", "undefined", ")", "{", "priority", "=", "0", ";", "}", "_insertProviderSorted", "(", "_inlineDocsProviders", ",", "provider", ",", "priority", ")", ";", "}" ]
Registers a new inline docs provider. When Quick Docs is invoked each registered provider is asked if it wants to provide inline docs given the current editor and cursor location. An optional priority parameter is used to give providers with higher priority an opportunity to provide an inline editor before providers with lower priority. @param {function(!Editor, !{line:number, ch:number}):?($.Promise|string)} provider @param {number=} priority The provider returns a promise that will be resolved with an InlineWidget, or returns a string indicating why the provider cannot respond to this case (or returns null to indicate no reason).
[ "Registers", "a", "new", "inline", "docs", "provider", ".", "When", "Quick", "Docs", "is", "invoked", "each", "registered", "provider", "is", "asked", "if", "it", "wants", "to", "provide", "inline", "docs", "given", "the", "current", "editor", "and", "cursor", "location", ".", "An", "optional", "priority", "parameter", "is", "used", "to", "give", "providers", "with", "higher", "priority", "an", "opportunity", "to", "provide", "an", "inline", "editor", "before", "providers", "with", "lower", "priority", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L410-L415
2,066
adobe/brackets
src/editor/EditorManager.js
openDocument
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
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); }
[ "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", ")", ";", "}" ]
Opens the specified document in the given pane @param {!Document} doc - the document to open @param {!Pane} pane - the pane to open the document in @param {!Object} editorOptions - If specified, contains editor options that can be passed to CodeMirror @return {boolean} true if the file can be opened, false if not
[ "Opens", "the", "specified", "document", "in", "the", "given", "pane" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L613-L621
2,067
adobe/brackets
src/editor/EditorManager.js
_handleRemoveFromPaneView
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
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); } }
[ "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", ")", ";", "}", "}" ]
file removed from pane handler. @param {jQuery.Event} e @param {File|Array.<File>} removedFiles - file, path or array of files or paths that are being removed
[ "file", "removed", "from", "pane", "handler", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/EditorManager.js#L691-L709
2,068
adobe/brackets
src/command/DefaultMenus.js
_setContextMenuItemsVisible
function _setContextMenuItemsVisible(enabled, items) { items.forEach(function (item) { CommandManager.get(item).setEnabled(enabled); }); }
javascript
function _setContextMenuItemsVisible(enabled, items) { items.forEach(function (item) { CommandManager.get(item).setEnabled(enabled); }); }
[ "function", "_setContextMenuItemsVisible", "(", "enabled", ",", "items", ")", "{", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "CommandManager", ".", "get", "(", "item", ")", ".", "setEnabled", "(", "enabled", ")", ";", "}", ")", ";", "}" ]
Disables menu items present in items if enabled is true. enabled is true if file is saved and present on user system. @param {boolean} enabled @param {array} items
[ "Disables", "menu", "items", "present", "in", "items", "if", "enabled", "is", "true", ".", "enabled", "is", "true", "if", "file", "is", "saved", "and", "present", "on", "user", "system", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/command/DefaultMenus.js#L43-L47
2,069
adobe/brackets
src/command/DefaultMenus.js
_setMenuItemsVisible
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
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]); }); } }
[ "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", "]", ")", ";", "}", ")", ";", "}", "}" ]
Checks if file saved and present on system and disables menu items accordingly
[ "Checks", "if", "file", "saved", "and", "present", "on", "system", "and", "disables", "menu", "items", "accordingly" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/command/DefaultMenus.js#L53-L63
2,070
adobe/brackets
src/filesystem/impls/appshell/node/FileWatcherManager.js
normalizeStats
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
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 }; }
[ "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", "}", ";", "}" ]
Transform Node's native fs.stats to a format that can be sent through domain @param {stats} nodeFsStats Node's fs.stats result @return {object} Can be consumed by new FileSystemStats(object); in Brackets
[ "Transform", "Node", "s", "native", "fs", ".", "stats", "to", "a", "format", "that", "can", "be", "sent", "through", "domain" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/filesystem/impls/appshell/node/FileWatcherManager.js#L46-L63
2,071
adobe/brackets
src/filesystem/impls/appshell/node/FileWatcherManager.js
_unwatchPath
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
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]; } } }
[ "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", "]", ";", "}", "}", "}" ]
Un-watch a file or directory. @private @param {string} path File or directory to unwatch.
[ "Un", "-", "watch", "a", "file", "or", "directory", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/filesystem/impls/appshell/node/FileWatcherManager.js#L70-L82
2,072
adobe/brackets
src/filesystem/impls/appshell/node/FileWatcherManager.js
unwatchPath
function unwatchPath(path) { Object.keys(_watcherMap).forEach(function (keyPath) { if (keyPath.indexOf(path) === 0) { _unwatchPath(keyPath); } }); }
javascript
function unwatchPath(path) { Object.keys(_watcherMap).forEach(function (keyPath) { if (keyPath.indexOf(path) === 0) { _unwatchPath(keyPath); } }); }
[ "function", "unwatchPath", "(", "path", ")", "{", "Object", ".", "keys", "(", "_watcherMap", ")", ".", "forEach", "(", "function", "(", "keyPath", ")", "{", "if", "(", "keyPath", ".", "indexOf", "(", "path", ")", "===", "0", ")", "{", "_unwatchPath", "(", "keyPath", ")", ";", "}", "}", ")", ";", "}" ]
Un-watch a file or directory. For directories, unwatch all descendants. @param {string} path File or directory to unwatch.
[ "Un", "-", "watch", "a", "file", "or", "directory", ".", "For", "directories", "unwatch", "all", "descendants", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/filesystem/impls/appshell/node/FileWatcherManager.js#L88-L94
2,073
adobe/brackets
src/filesystem/impls/appshell/node/FileWatcherManager.js
watchPath
function watchPath(path, ignored) { if (_watcherMap.hasOwnProperty(path)) { return; } return _watcherImpl.watchPath(path, ignored, _watcherMap, _domainManager); }
javascript
function watchPath(path, ignored) { if (_watcherMap.hasOwnProperty(path)) { return; } return _watcherImpl.watchPath(path, ignored, _watcherMap, _domainManager); }
[ "function", "watchPath", "(", "path", ",", "ignored", ")", "{", "if", "(", "_watcherMap", ".", "hasOwnProperty", "(", "path", ")", ")", "{", "return", ";", "}", "return", "_watcherImpl", ".", "watchPath", "(", "path", ",", "ignored", ",", "_watcherMap", ",", "_domainManager", ")", ";", "}" ]
Watch a file or directory. @param {string} path File or directory to watch. @param {Array<string>} ignored List of entries to ignore during watching.
[ "Watch", "a", "file", "or", "directory", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/filesystem/impls/appshell/node/FileWatcherManager.js#L101-L106
2,074
adobe/brackets
src/document/DocumentCommandHandlers.js
_shortTitleForDocument
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
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); } }
[ "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", ")", ";", "}", "}" ]
Returns a short title for a given document. @param {Document} doc - the document to compute the short title for @return {string} - a short title for doc.
[ "Returns", "a", "short", "title", "for", "a", "given", "document", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L221-L232
2,075
adobe/brackets
src/document/DocumentCommandHandlers.js
handleCurrentFileChange
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
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(); }
[ "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", "(", ")", ";", "}" ]
Handles currentFileChange and filenameChanged events and updates the titlebar
[ "Handles", "currentFileChange", "and", "filenameChanged", "events", "and", "updates", "the", "titlebar" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L237-L254
2,076
adobe/brackets
src/document/DocumentCommandHandlers.js
handleDirtyChange
function handleDirtyChange(event, changedDoc) { var currentDoc = DocumentManager.getCurrentDocument(); if (currentDoc && changedDoc.file.fullPath === currentDoc.file.fullPath) { _updateTitle(); } }
javascript
function handleDirtyChange(event, changedDoc) { var currentDoc = DocumentManager.getCurrentDocument(); if (currentDoc && changedDoc.file.fullPath === currentDoc.file.fullPath) { _updateTitle(); } }
[ "function", "handleDirtyChange", "(", "event", ",", "changedDoc", ")", "{", "var", "currentDoc", "=", "DocumentManager", ".", "getCurrentDocument", "(", ")", ";", "if", "(", "currentDoc", "&&", "changedDoc", ".", "file", ".", "fullPath", "===", "currentDoc", ".", "file", ".", "fullPath", ")", "{", "_updateTitle", "(", ")", ";", "}", "}" ]
Handles dirtyFlagChange event and updates the title bar if necessary
[ "Handles", "dirtyFlagChange", "event", "and", "updates", "the", "title", "bar", "if", "necessary" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L259-L265
2,077
adobe/brackets
src/document/DocumentCommandHandlers.js
showFileOpenError
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
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) ) ); }
[ "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", ")", ")", ")", ";", "}" ]
Shows an error dialog indicating that the given file could not be opened due to the given error @param {!FileSystemError} name @return {!Dialog}
[ "Shows", "an", "error", "dialog", "indicating", "that", "the", "given", "file", "could", "not", "be", "opened", "due", "to", "the", "given", "error" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L272-L282
2,078
adobe/brackets
src/document/DocumentCommandHandlers.js
handleDocumentOpen
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
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(); }
[ "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", "(", ")", ";", "}" ]
Opens the given file, makes it the current file, does NOT add it to the workingset @param {FileCommandData} commandData fullPath: File to open; silent: optional flag to suppress error messages; paneId: optional PaneId (defaults to active pane) @return {$.Promise} a jQuery promise that will be resolved with @type {Document}
[ "Opens", "the", "given", "file", "makes", "it", "the", "current", "file", "does", "NOT", "add", "it", "to", "the", "workingset" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L525-L542
2,079
adobe/brackets
src/document/DocumentCommandHandlers.js
handleFileAddToWorkingSetAndOpen
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
Opens the given file, makes it the current file, AND adds it to the workingset @param {!PaneCommandData} commandData - record with the following properties: fullPath: File to open; index: optional index to position in workingset (defaults to last); silent: optional flag to suppress error messages; forceRedraw: flag to force the working set view redraw; paneId: optional PaneId (defaults to active pane) @return {$.Promise} a jQuery promise that will be resolved with a @type {File}
[ "Opens", "the", "given", "file", "makes", "it", "the", "current", "file", "AND", "adds", "it", "to", "the", "workingset" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L554-L560
2,080
adobe/brackets
src/document/DocumentCommandHandlers.js
_handleNewItemInProject
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
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)); }
[ "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", ")", ")", ";", "}" ]
Bottleneck function for creating new files and folders in the project tree. @private @param {boolean} isFolder - true if creating a new folder, false if creating a new file
[ "Bottleneck", "function", "for", "creating", "new", "files", "and", "folders", "in", "the", "project", "tree", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L644-L676
2,081
adobe/brackets
src/document/DocumentCommandHandlers.js
createWithSuggestedName
function createWithSuggestedName(suggestedName) { return ProjectManager.createNewItem(baseDirEntry, suggestedName, false, isFolder) .always(function () { fileNewInProgress = false; }); }
javascript
function createWithSuggestedName(suggestedName) { return ProjectManager.createNewItem(baseDirEntry, suggestedName, false, isFolder) .always(function () { fileNewInProgress = false; }); }
[ "function", "createWithSuggestedName", "(", "suggestedName", ")", "{", "return", "ProjectManager", ".", "createNewItem", "(", "baseDirEntry", ",", "suggestedName", ",", "false", ",", "isFolder", ")", ".", "always", "(", "function", "(", ")", "{", "fileNewInProgress", "=", "false", ";", "}", ")", ";", "}" ]
Create the new node. The createNewItem function does all the heavy work of validating file name, creating the new file and selecting.
[ "Create", "the", "new", "node", ".", "The", "createNewItem", "function", "does", "all", "the", "heavy", "work", "of", "validating", "file", "name", "creating", "the", "new", "file", "and", "selecting", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L669-L672
2,082
adobe/brackets
src/document/DocumentCommandHandlers.js
doSave
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
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(); }
[ "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", "(", ")", ";", "}" ]
Saves a document to its existing path. Does NOT support untitled documents. @param {!Document} docToSave @param {boolean=} force Ignore CONTENTS_MODIFIED errors from the FileSystem @return {$.Promise} a promise that is resolved with the File of docToSave (to mirror the API of _doSaveAs()). Rejected in case of IO error (after error dialog dismissed).
[ "Saves", "a", "document", "to", "its", "existing", "path", ".", "Does", "NOT", "support", "untitled", "documents", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L744-L836
2,083
adobe/brackets
src/document/DocumentCommandHandlers.js
_doRevert
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
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(); }
[ "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", "(", ")", ";", "}" ]
Reverts the Document to the current contents of its file on disk. Discards any unsaved changes in the Document. @private @param {Document} doc @param {boolean=} suppressError If true, then a failure to read the file will be ignored and the resulting promise will be resolved rather than rejected. @return {$.Promise} a Promise that's resolved when done, or (if suppressError is false) rejected with a FileSystemError if the file cannot be read (after showing an error dialog to the user).
[ "Reverts", "the", "Document", "to", "the", "current", "contents", "of", "its", "file", "on", "disk", ".", "Discards", "any", "unsaved", "changes", "in", "the", "Document", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L849-L869
2,084
adobe/brackets
src/document/DocumentCommandHandlers.js
_configureEditorAndResolve
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
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); }
[ "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", ")", ";", "}" ]
Reconstruct old doc's editor's view state, & finally resolve overall promise
[ "Reconstruct", "old", "doc", "s", "editor", "s", "view", "state", "&", "finally", "resolve", "overall", "promise" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L902-L911
2,085
adobe/brackets
src/document/DocumentCommandHandlers.js
openNewFile
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
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(); }); }
[ "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", "(", ")", ";", "}", ")", ";", "}" ]
Replace old document with new one in open editor & workingset
[ "Replace", "old", "document", "with", "new", "one", "in", "open", "editor", "&", "workingset" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L914-L936
2,086
adobe/brackets
src/document/DocumentCommandHandlers.js
handleFileSave
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
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(); }
[ "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", "(", ")", ";", "}" ]
Saves the given file. If no file specified, assumes the current document. @param {?{doc: ?Document}} commandData Document to close, or null @return {$.Promise} resolved with the saved document's File (which MAY DIFFER from the doc passed in, if the doc was untitled). Rejected in case of IO error (after error dialog dismissed), or if doc was untitled and the Save dialog was canceled (will be rejected with USER_CANCELED object).
[ "Saves", "the", "given", "file", ".", "If", "no", "file", "specified", "assumes", "the", "current", "document", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L1049-L1071
2,087
adobe/brackets
src/document/DocumentCommandHandlers.js
handleFileQuit
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
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(); } ); }
[ "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", "(", ")", ";", "}", ")", ";", "}" ]
Closes the window, then quits the app
[ "Closes", "the", "window", "then", "quits", "the", "app" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L1507-L1518
2,088
adobe/brackets
src/document/DocumentCommandHandlers.js
_disableCache
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
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(); }
[ "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", "(", ")", ";", "}" ]
Disables Brackets' cache via the remote debugging protocol. @return {$.Promise} A jQuery promise that will be resolved when the cache is disabled and be rejected in any other case
[ "Disables", "Brackets", "cache", "via", "the", "remote", "debugging", "protocol", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L1639-L1670
2,089
adobe/brackets
src/document/DocumentCommandHandlers.js
browserReload
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
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; }); }
[ "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", ";", "}", ")", ";", "}" ]
Does a full reload of the browser window @param {string} href The url to reload into the window
[ "Does", "a", "full", "reload", "of", "the", "browser", "window" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L1676-L1713
2,090
adobe/brackets
src/document/DocumentCommandHandlers.js
handleReload
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
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); }
[ "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", ")", ";", "}" ]
Restarts brackets Handler @param {boolean=} loadWithoutExtensions - true to restart without extensions, otherwise extensions are loadeed as it is durning a typical boot
[ "Restarts", "brackets", "Handler" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/DocumentCommandHandlers.js#L1720-L1750
2,091
adobe/brackets
src/extensions/default/SVGCodeHints/main.js
getTagAttributes
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
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]; }
[ "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", "]", ";", "}" ]
Returns a list of attributes used by a tag. @param {string} tagName name of the SVG tag. @return {Array.<string>} list of attributes.
[ "Returns", "a", "list", "of", "attributes", "used", "by", "a", "tag", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/SVGCodeHints/main.js#L76-L93
2,092
adobe/brackets
src/extensions/default/QuickView/main.js
normalizeGradientExpressionForQuickview
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
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; }
[ "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", ";", "}" ]
Normalizes px color stops to %
[ "Normalizes", "px", "color", "stops", "to", "%" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/QuickView/main.js#L335-L389
2,093
adobe/brackets
src/extensions/default/QuickView/main.js
showPreview
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
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); } } }
[ "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", ")", ";", "}", "}", "}" ]
Changes the current hidden popoverState to visible, showing it in the UI and highlighting its matching text in the editor.
[ "Changes", "the", "current", "hidden", "popoverState", "to", "visible", "showing", "it", "in", "the", "UI", "and", "highlighting", "its", "matching", "text", "in", "the", "editor", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/QuickView/main.js#L616-L665
2,094
adobe/brackets
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
getFunctionArgs
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
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 []; }
[ "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", "[", "]", ";", "}" ]
Gets the arguments to a function in an array @param {object} args - the arguments object @returns {Array} - array of actual arguments
[ "Gets", "the", "arguments", "to", "a", "function", "in", "an", "array" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L75-L85
2,095
adobe/brackets
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
postMessageToBrackets
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
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]); }
[ "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", "]", ")", ";", "}" ]
Posts messages to brackets @param {string} messageId - Message to be passed
[ "Posts", "messages", "to", "brackets" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L92-L106
2,096
adobe/brackets
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
validateChecksum
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
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); } }
[ "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", ")", ";", "}", "}" ]
Validates the checksum of a file against a given checksum @param {object} params - json containing { filePath - path to the file, expectedChecksum - the checksum to validate against }
[ "Validates", "the", "checksum", "of", "a", "file", "against", "a", "given", "checksum" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L128-L180
2,097
adobe/brackets
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
parseInstallerLog
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
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(""); }); }
[ "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", "(", "\"\"", ")", ";", "}", ")", ";", "}" ]
Parse the Installer log and search for a error strings one it finds the line which has any of error String it return that line and exit
[ "Parse", "the", "Installer", "log", "and", "search", "for", "a", "error", "strings", "one", "it", "finds", "the", "line", "which", "has", "any", "of", "error", "String", "it", "return", "that", "line", "and", "exit" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L187-L215
2,098
adobe/brackets
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
checkInstallerStatus
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
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); }); }
[ "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", ")", ";", "}", ")", ";", "}" ]
one it finds the line which has any of error String after parsing the Log it notifies the bracket. @param{Object} searchParams is object contains Information Error String Encoding of Log File Update Diectory Path.
[ "one", "it", "finds", "the", "line", "which", "has", "any", "of", "error", "String", "after", "parsing", "the", "Log", "it", "notifies", "the", "bracket", "." ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L224-L264
2,099
adobe/brackets
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
downloadInstaller
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
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); } }
[ "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", ")", ";", "}", "}" ]
Downloads the installer for latest Brackets release @param {boolean} sendInfo - true if download status info needs to be sent back to Brackets, false otherwise @param {object} [updateParams=_updateParams] - json containing update parameters
[ "Downloads", "the", "installer", "for", "latest", "Brackets", "release" ]
d5d00d43602c438266d32b8eda8f8a3ca937b524
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L272-L324