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
list | docstring
stringlengths 4
11.8k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
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
|
train
|
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",
")",
";",
"var",
"path",
"=",
"url",
".",
"slice",
"(",
"brackets",
".",
"platform",
"===",
"\"win\"",
"?",
"8",
":",
"7",
")",
";",
"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
|
train
|
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",
")",
"{",
"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
|
train
|
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",
"}"
] |
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
|
train
|
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",
")",
")",
"{",
"activeQuote",
"=",
"activeQuote",
"?",
"undefined",
":",
"src",
"[",
"i",
"]",
";",
"}",
"else",
"if",
"(",
"!",
"activeQuote",
")",
"{",
"if",
"(",
"comments",
"&&",
"!",
"isComment",
"&&",
"src",
".",
"substr",
"(",
"i",
",",
"comments",
"[",
"0",
"]",
".",
"length",
")",
"===",
"comments",
"[",
"0",
"]",
")",
"{",
"isComment",
"=",
"true",
";",
"i",
"+=",
"comments",
"[",
"0",
"]",
".",
"length",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"isComment",
")",
"{",
"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",
")",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"===",
"\"<!--\"",
")",
"{",
"to",
"=",
"_find",
"(",
"src",
",",
"\"",
",",
"from",
"+",
"4",
")",
";",
"inc",
"=",
"3",
";",
"}",
"else",
"if",
"(",
"src",
".",
"substr",
"(",
"from",
",",
"7",
")",
".",
"toLowerCase",
"(",
")",
"===",
"\"<script\"",
")",
"{",
"to",
"=",
"_find",
"(",
"src",
".",
"toLowerCase",
"(",
")",
",",
"\"</script>\"",
",",
"from",
"+",
"7",
")",
";",
"inc",
"=",
"9",
";",
"}",
"else",
"if",
"(",
"src",
".",
"substr",
"(",
"from",
",",
"6",
")",
".",
"toLowerCase",
"(",
")",
"===",
"\"<style\"",
")",
"{",
"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
|
train
|
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",
")",
"{",
"content",
"=",
"content",
".",
"replace",
"(",
"/",
"^<\\S+\\s*",
"/",
",",
"\"\"",
")",
";",
"content",
"=",
"content",
".",
"replace",
"(",
"/",
"\\s*\\/?>$",
"/",
",",
"\"\"",
")",
";",
"if",
"(",
"content",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"var",
"index",
",",
"key",
",",
"value",
";",
"var",
"attributes",
"=",
"{",
"}",
";",
"_findEach",
"(",
"content",
",",
"[",
"/",
"\\s",
"/",
",",
"1",
"]",
",",
"true",
",",
"undefined",
",",
"function",
"each",
"(",
"item",
")",
"{",
"index",
"=",
"item",
".",
"search",
"(",
"\"=\"",
")",
";",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"return",
";",
"}",
"key",
"=",
"item",
".",
"substr",
"(",
"0",
",",
"index",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"key",
".",
"length",
"===",
"0",
")",
"{",
"return",
";",
"}",
"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
|
train
|
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",
"]",
"!==",
"\"<\"",
")",
"{",
"payload",
".",
"nodeType",
"=",
"3",
";",
"payload",
".",
"nodeValue",
"=",
"content",
";",
"}",
"else",
"if",
"(",
"content",
".",
"substr",
"(",
"0",
",",
"4",
")",
"===",
"\"<!--\"",
")",
"{",
"payload",
".",
"nodeType",
"=",
"8",
";",
"payload",
".",
"nodeValue",
"=",
"content",
".",
"substr",
"(",
"4",
",",
"content",
".",
"length",
"-",
"7",
")",
";",
"}",
"else",
"if",
"(",
"content",
"[",
"1",
"]",
"===",
"\"!\"",
")",
"{",
"payload",
".",
"nodeType",
"=",
"10",
";",
"}",
"else",
"{",
"payload",
".",
"nodeType",
"=",
"1",
";",
"payload",
".",
"nodeName",
"=",
"/",
"^<([^>\\s]+)",
"/",
".",
"exec",
"(",
"content",
")",
"[",
"1",
"]",
".",
"toUpperCase",
"(",
")",
";",
"payload",
".",
"attributes",
"=",
"_extractAttributes",
"(",
"content",
")",
";",
"if",
"(",
"payload",
".",
"nodeName",
"[",
"0",
"]",
"===",
"\"/\"",
")",
"{",
"payload",
".",
"nodeName",
"=",
"payload",
".",
"nodeName",
".",
"substr",
"(",
"1",
")",
";",
"payload",
".",
"closing",
"=",
"true",
";",
"}",
"if",
"(",
"content",
"[",
"content",
".",
"length",
"-",
"2",
"]",
"===",
"\"/\"",
")",
"{",
"payload",
".",
"closed",
"=",
"true",
";",
"}",
"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
|
train
|
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",
")",
"{",
"range",
"=",
"_findTag",
"(",
"src",
",",
"index",
")",
";",
"if",
"(",
"!",
"range",
")",
"{",
"range",
"=",
"{",
"from",
":",
"src",
".",
"length",
",",
"length",
":",
"0",
"}",
";",
"}",
"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",
")",
";",
"}",
"}",
"if",
"(",
"range",
".",
"length",
">",
"0",
")",
"{",
"payload",
"=",
"extractPayload",
"(",
"src",
".",
"substr",
"(",
"range",
".",
"from",
",",
"range",
".",
"length",
")",
")",
";",
"payload",
".",
"sourceOffset",
"=",
"range",
".",
"from",
";",
"payload",
".",
"sourceLength",
"=",
"range",
".",
"length",
";",
"callback",
"(",
"payload",
")",
";",
"}",
"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
|
train
|
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",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"return",
"true",
";",
"}",
"else",
"if",
"(",
"len",
"===",
"1",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"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
|
train
|
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",
")",
"{",
"types",
".",
"forEach",
"(",
"function",
"(",
"value",
")",
"{",
"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
|
train
|
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",
"(",
")",
";",
"FileSystem",
".",
"resolve",
"(",
"path",
",",
"function",
"(",
"err",
",",
"item",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"item",
".",
"isFile",
")",
"{",
"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",
")",
"{",
"ProjectManager",
".",
"openProject",
"(",
"path",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"result",
".",
"resolve",
"(",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
")",
"{",
"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
|
train
|
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",
"{",
"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
|
train
|
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",
";",
"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",
"--",
";",
"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
|
train
|
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",
")",
"{",
"if",
"(",
"(",
"visible",
"&&",
"curEditor",
"===",
"editor",
")",
"||",
"(",
"!",
"visible",
"&&",
"!",
"editor",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"visible",
")",
"{",
"console",
".",
"assert",
"(",
"!",
"editor",
")",
";",
"editor",
"=",
"curEditor",
";",
"if",
"(",
"editor",
".",
"isTextSubset",
"(",
")",
")",
"{",
"return",
";",
"}",
"var",
"$sb",
"=",
"_getScrollbar",
"(",
"editor",
")",
",",
"$overlay",
"=",
"$",
"(",
"\"<div class='tickmark-track'></div>\"",
")",
";",
"$sb",
".",
"parent",
"(",
")",
".",
"append",
"(",
"$overlay",
")",
";",
"_calcScaling",
"(",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"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",
")",
";",
"}",
")",
";",
"}",
"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",
")",
";",
"}",
")",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
";",
"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",
";",
"}",
"if",
"(",
"message",
"&&",
"message",
".",
"substr",
"(",
"0",
",",
"8",
")",
"===",
"\"Uncaught\"",
")",
"{",
"message",
"=",
"message",
".",
"substr",
"(",
"9",
")",
";",
"}",
"var",
"data",
"=",
"error",
".",
"data",
";",
"if",
"(",
"Array",
".",
"isArray",
"(",
"data",
")",
")",
"{",
"message",
"+=",
"\"\\n\"",
"+",
"\\n",
";",
"}",
"data",
".",
"join",
"(",
"\"\\n\"",
")",
"}"
] |
Triggered by Inspector.error
|
[
"Triggered",
"by",
"Inspector",
".",
"error"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/LiveDevelopment/LiveDevelopment.js#L473-L497
|
train
|
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",
"(",
"_loadAgentsPromise",
")",
"{",
"return",
"_loadAgentsPromise",
";",
"}",
"var",
"result",
"=",
"new",
"$",
".",
"Deferred",
"(",
")",
",",
"allAgentsPromise",
";",
"_loadAgentsPromise",
"=",
"result",
".",
"promise",
"(",
")",
";",
"_setStatus",
"(",
"STATUS_LOADING_AGENTS",
")",
";",
"allAgentsPromise",
"=",
"Async",
".",
"doInParallel",
"(",
"getEnabledAgents",
"(",
")",
",",
"function",
"(",
"name",
")",
"{",
"return",
"_invokeAgentMethod",
"(",
"name",
",",
"\"load\"",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"_loadedAgentNames",
".",
"push",
"(",
"name",
")",
";",
"}",
")",
";",
"}",
",",
"true",
")",
";",
"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",
"(",
")",
"{",
"_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
|
train
|
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
|
train
|
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",
")",
"{",
"return",
"_loadAgentsPromise",
";",
"}",
"unloadAgents",
"(",
")",
";",
"_",
".",
"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
|
train
|
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",
")",
"{",
"Inspector",
".",
"Page",
".",
"on",
"(",
"\"frameNavigated.livedev\"",
",",
"_onFrameNavigated",
")",
";",
"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
|
train
|
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",
")",
"{",
"_setStatus",
"(",
"STATUS_CONNECTING",
")",
";",
"_createLiveDocumentForFrame",
"(",
"initialDoc",
")",
";",
"_server",
".",
"start",
"(",
")",
";",
"Inspector",
".",
"one",
"(",
"\"connect\"",
",",
"_onConnect",
")",
";",
"_openInterstitialPage",
"(",
")",
";",
"_openDeferred",
".",
"done",
"(",
"function",
"(",
")",
"{",
"EditorManager",
".",
"on",
"(",
"\"activeEditorChange\"",
",",
"onActiveEditorChange",
")",
";",
"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
|
train
|
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",
"(",
"_isPromisePending",
"(",
"_closeDeferred",
")",
")",
"{",
"return",
"_closeDeferred",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"open",
"(",
"restart",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"!",
"restart",
")",
"{",
"if",
"(",
"_isPromisePending",
"(",
"_openDeferred",
")",
")",
"{",
"return",
"_openDeferred",
";",
"}",
"else",
"{",
"_openDeferred",
"=",
"new",
"$",
".",
"Deferred",
"(",
")",
";",
"_openDeferred",
".",
"always",
"(",
"function",
"(",
")",
"{",
"_openDeferred",
"=",
"null",
";",
"}",
")",
";",
"}",
"}",
"HealthLogger",
".",
"sendAnalyticsData",
"(",
"\"livePreviewOpen\"",
",",
"\"usage\"",
",",
"\"livePreview\"",
",",
"\"open\"",
")",
";",
"_regServers",
".",
"push",
"(",
"LiveDevServerManager",
".",
"registerServer",
"(",
"{",
"create",
":",
"_createUserServer",
"}",
",",
"99",
")",
")",
";",
"_regServers",
".",
"push",
"(",
"LiveDevServerManager",
".",
"registerServer",
"(",
"{",
"create",
":",
"_createFileServer",
"}",
",",
"0",
")",
")",
";",
"_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",
")",
";",
"}",
"}",
"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
|
train
|
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",
"(",
")",
";",
"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
|
train
|
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",
")",
")",
")",
"{",
"_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
|
train
|
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",
")",
";",
"CSSAgent",
".",
"on",
"(",
"\"styleSheetAdded.livedev\"",
",",
"_styleSheetAdded",
")",
";",
"MainViewManager",
".",
"on",
"(",
"\"currentFileChange\"",
",",
"_onFileChanged",
")",
";",
"DocumentManager",
".",
"on",
"(",
"\"documentSaved\"",
",",
"_onDocumentSaved",
")",
".",
"on",
"(",
"\"dirtyFlagChange\"",
",",
"_onDirtyFlagChange",
")",
";",
"ProjectManager",
".",
"on",
"(",
"\"beforeProjectClose beforeAppClose\"",
",",
"close",
")",
";",
"_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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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",
")",
"{",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"PerfUtils",
".",
"markStart",
"(",
"PerfUtils",
".",
"INLINE_WIDGET_CLOSE",
")",
";",
"inlineWidget",
".",
"close",
"(",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"PerfUtils",
".",
"addMeasurement",
"(",
"PerfUtils",
".",
"INLINE_WIDGET_CLOSE",
")",
";",
"result",
".",
"resolve",
"(",
"false",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"_openInlineWidget",
"(",
"currentEditor",
",",
"providers",
",",
"errorMsg",
")",
".",
"done",
"(",
"function",
"(",
")",
"{",
"result",
".",
"resolve",
"(",
"true",
")",
";",
"}",
")",
".",
"fail",
"(",
"function",
"(",
")",
"{",
"result",
".",
"reject",
"(",
")",
";",
"}",
")",
";",
"}",
"}",
"else",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
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\"",
"+",
"\\t",
")",
";",
"(",
"!",
"doc",
"||",
"doc",
".",
"file",
".",
"fullPath",
")",
"if",
"(",
"doc",
"&&",
"pane",
")",
"{",
"_showEditor",
"(",
"doc",
",",
"pane",
",",
"editorOptions",
")",
";",
"}",
"}"
] |
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
|
train
|
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",
")",
";",
"}",
"}",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"var",
"mtime",
"=",
"Math",
".",
"floor",
"(",
"nodeFsStats",
".",
"mtime",
".",
"getTime",
"(",
")",
"/",
"1000",
")",
"*",
"1000",
";",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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",
"(",
"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
|
train
|
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",
";",
"}",
"_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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"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
|
train
|
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
|
train
|
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",
";",
"var",
"baseDirEntry",
",",
"selected",
"=",
"ProjectManager",
".",
"getFileTreeContext",
"(",
")",
";",
"if",
"(",
"(",
"!",
"selected",
")",
"||",
"(",
"selected",
"instanceof",
"InMemoryFile",
")",
")",
"{",
"selected",
"=",
"ProjectManager",
".",
"getProjectRoot",
"(",
")",
";",
"}",
"if",
"(",
"selected",
".",
"isFile",
")",
"{",
"baseDirEntry",
"=",
"FileSystem",
".",
"getDirectoryForPath",
"(",
"selected",
".",
"parentPath",
")",
";",
"}",
"baseDirEntry",
"=",
"baseDirEntry",
"||",
"selected",
";",
"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
|
train
|
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
|
train
|
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",
")",
"{",
"doSave",
"(",
"docToSave",
",",
"true",
")",
".",
"then",
"(",
"result",
".",
"resolve",
",",
"result",
".",
"reject",
")",
";",
"}",
"else",
"if",
"(",
"id",
"===",
"Dialogs",
".",
"DIALOG_BTN_SAVE_AS",
")",
"{",
"handleFileSaveAs",
"(",
"{",
"doc",
":",
"docToSave",
"}",
")",
".",
"then",
"(",
"result",
".",
"resolve",
",",
"result",
".",
"reject",
")",
";",
"}",
"}",
")",
";",
"}",
"function",
"trySave",
"(",
")",
"{",
"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",
")",
"{",
"docToSave",
".",
"file",
".",
"stat",
"(",
"function",
"(",
"err",
",",
"stat",
")",
"{",
"if",
"(",
"!",
"err",
"&&",
"docToSave",
".",
"keepChangesTime",
"===",
"stat",
".",
"mtime",
".",
"getTime",
"(",
")",
")",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
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",
")",
"{",
"fileOpenPromise",
"=",
"FileViewController",
".",
"openAndSelectDocument",
"(",
"path",
",",
"FileViewController",
".",
"PROJECT_MANAGER",
")",
";",
"}",
"else",
"{",
"var",
"info",
"=",
"MainViewManager",
".",
"findInAllWorkingSets",
"(",
"doc",
".",
"file",
".",
"fullPath",
")",
".",
"shift",
"(",
")",
";",
"MainViewManager",
".",
"_removeView",
"(",
"info",
".",
"paneId",
",",
"doc",
".",
"file",
",",
"true",
")",
";",
"fileOpenPromise",
"=",
"handleFileAddToWorkingSetAndOpen",
"(",
"{",
"fullPath",
":",
"path",
",",
"paneId",
":",
"info",
".",
"paneId",
",",
"index",
":",
"info",
".",
"index",
",",
"forceRedraw",
":",
"true",
"}",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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",
"(",
")",
"{",
"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
|
train
|
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",
")",
";",
"_socket",
".",
"onopen",
"=",
"function",
"_onConnect",
"(",
")",
"{",
"_socket",
".",
"send",
"(",
"JSON",
".",
"stringify",
"(",
"{",
"id",
":",
"1",
",",
"method",
":",
"\"Network.setCacheDisabled\"",
",",
"params",
":",
"{",
"\"cacheDisabled\"",
":",
"true",
"}",
"}",
")",
")",
";",
"}",
";",
"_socket",
".",
"onmessage",
"=",
"function",
"_onMessage",
"(",
"e",
")",
"{",
"_socket",
".",
"close",
"(",
")",
";",
"result",
".",
"resolve",
"(",
")",
";",
"}",
";",
"_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
|
train
|
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",
"(",
")",
"{",
"try",
"{",
"ProjectManager",
".",
"trigger",
"(",
"\"beforeAppClose\"",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"console",
".",
"error",
"(",
"ex",
")",
";",
"}",
"_disableCache",
"(",
")",
".",
"always",
"(",
"function",
"(",
")",
"{",
"_",
".",
"forEach",
"(",
"Menus",
".",
"getAllMenus",
"(",
")",
",",
"function",
"(",
"value",
",",
"key",
")",
"{",
"Menus",
".",
"removeMenu",
"(",
"key",
")",
";",
"}",
")",
";",
"var",
"fragment",
"=",
"href",
".",
"indexOf",
"(",
"\"#\"",
")",
";",
"if",
"(",
"fragment",
"!==",
"-",
"1",
")",
"{",
"href",
"=",
"href",
".",
"substr",
"(",
"0",
",",
"fragment",
")",
";",
"}",
"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
|
train
|
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",
"(",
")",
";",
"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",
"(",
")",
";",
"}",
"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
|
train
|
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
|
train
|
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",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"params",
".",
"length",
";",
"i",
"++",
")",
"{",
"args",
"=",
"params",
"[",
"i",
"]",
".",
"split",
"(",
"\" \"",
")",
";",
"if",
"(",
"hasLengthInPixels",
"(",
"args",
")",
")",
"{",
"thisSize",
"=",
"parseFloat",
"(",
"args",
"[",
"1",
"]",
")",
";",
"upperBound",
"=",
"Math",
".",
"max",
"(",
"upperBound",
",",
"thisSize",
")",
";",
"if",
"(",
"thisSize",
"<",
"0",
")",
"{",
"lowerBound",
"=",
"Math",
".",
"min",
"(",
"lowerBound",
",",
"thisSize",
")",
";",
"}",
"}",
"}",
"lowerBound",
"=",
"Math",
".",
"abs",
"(",
"lowerBound",
")",
";",
"upperBound",
"+=",
"lowerBound",
";",
"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",
"(",
"\" \"",
")",
";",
"}",
"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
|
train
|
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",
";",
"if",
"(",
"!",
"editor",
")",
"{",
"editor",
"=",
"getHoveredEditor",
"(",
"lastMousePos",
")",
";",
"}",
"if",
"(",
"!",
"editor",
"||",
"!",
"editor",
".",
"_codeMirror",
")",
"{",
"hidePreview",
"(",
")",
";",
"return",
";",
"}",
"cm",
"=",
"editor",
".",
"_codeMirror",
";",
"var",
"pos",
"=",
"cm",
".",
"coordsChar",
"(",
"{",
"left",
":",
"lastMousePos",
".",
"clientX",
",",
"top",
":",
"lastMousePos",
".",
"clientY",
"}",
")",
";",
"if",
"(",
"pos",
".",
"ch",
">=",
"editor",
".",
"document",
".",
"getLine",
"(",
"pos",
".",
"line",
")",
".",
"length",
")",
"{",
"return",
";",
"}",
"if",
"(",
"popover",
")",
"{",
"popoverState",
"=",
"popover",
";",
"}",
"else",
"{",
"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
|
train
|
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
|
train
|
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
|
train
|
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
|
train
|
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'",
")",
",",
"\\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",
")",
";",
"}"
] |
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
|
train
|
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
|
train
|
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
|
train
|
adobe/brackets
|
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
|
performCleanup
|
function performCleanup(requester, filesToCache, notifyBack) {
var currentRequester = requester || "";
function filterFilesAndNotify(files, filesToCacheArr, notifyBackToBrackets) {
files.forEach(function (file) {
var fileExt = path.extname(path.basename(file));
if (filesToCacheArr.indexOf(fileExt) < 0) {
var fileFullPath = updateDir + '/' + file;
try {
fs.removeSync(fileFullPath);
} catch (e) {
console.log("AutoUpdate : Exception occured in removing ", fileFullPath, e);
}
}
});
if (notifyBackToBrackets) {
postMessageToBrackets(MessageIds.NOTIFY_SAFE_TO_DOWNLOAD, currentRequester);
}
}
fs.stat(updateDir)
.then(function (stats) {
if (stats) {
if (filesToCache) {
fs.readdir(updateDir)
.then(function (files) {
filterFilesAndNotify(files, filesToCache, notifyBack);
})
.catch(function (err) {
console.log("AutoUpdate : Error in Reading Update Dir for Cleanup : " + err.toString());
postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
currentRequester, nodeErrorMessages.UPDATEDIR_READ_FAILED);
});
} else {
fs.remove(updateDir)
.then(function () {
console.log('AutoUpdate : Update Directory in AppData Cleaned: Complete');
})
.catch(function (err) {
console.log("AutoUpdate : Error in Cleaning Update Dir : " + err.toString());
postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED);
});
}
}
})
.catch(function (err) {
console.log("AutoUpdate : Error in Reading Update Dir stats for Cleanup : " + err.toString());
postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED);
});
}
|
javascript
|
function performCleanup(requester, filesToCache, notifyBack) {
var currentRequester = requester || "";
function filterFilesAndNotify(files, filesToCacheArr, notifyBackToBrackets) {
files.forEach(function (file) {
var fileExt = path.extname(path.basename(file));
if (filesToCacheArr.indexOf(fileExt) < 0) {
var fileFullPath = updateDir + '/' + file;
try {
fs.removeSync(fileFullPath);
} catch (e) {
console.log("AutoUpdate : Exception occured in removing ", fileFullPath, e);
}
}
});
if (notifyBackToBrackets) {
postMessageToBrackets(MessageIds.NOTIFY_SAFE_TO_DOWNLOAD, currentRequester);
}
}
fs.stat(updateDir)
.then(function (stats) {
if (stats) {
if (filesToCache) {
fs.readdir(updateDir)
.then(function (files) {
filterFilesAndNotify(files, filesToCache, notifyBack);
})
.catch(function (err) {
console.log("AutoUpdate : Error in Reading Update Dir for Cleanup : " + err.toString());
postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
currentRequester, nodeErrorMessages.UPDATEDIR_READ_FAILED);
});
} else {
fs.remove(updateDir)
.then(function () {
console.log('AutoUpdate : Update Directory in AppData Cleaned: Complete');
})
.catch(function (err) {
console.log("AutoUpdate : Error in Cleaning Update Dir : " + err.toString());
postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED);
});
}
}
})
.catch(function (err) {
console.log("AutoUpdate : Error in Reading Update Dir stats for Cleanup : " + err.toString());
postMessageToBrackets(MessageIds.SHOW_ERROR_MESSAGE,
currentRequester, nodeErrorMessages.UPDATEDIR_CLEAN_FAILED);
});
}
|
[
"function",
"performCleanup",
"(",
"requester",
",",
"filesToCache",
",",
"notifyBack",
")",
"{",
"var",
"currentRequester",
"=",
"requester",
"||",
"\"\"",
";",
"function",
"filterFilesAndNotify",
"(",
"files",
",",
"filesToCacheArr",
",",
"notifyBackToBrackets",
")",
"{",
"files",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"var",
"fileExt",
"=",
"path",
".",
"extname",
"(",
"path",
".",
"basename",
"(",
"file",
")",
")",
";",
"if",
"(",
"filesToCacheArr",
".",
"indexOf",
"(",
"fileExt",
")",
"<",
"0",
")",
"{",
"var",
"fileFullPath",
"=",
"updateDir",
"+",
"'/'",
"+",
"file",
";",
"try",
"{",
"fs",
".",
"removeSync",
"(",
"fileFullPath",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"console",
".",
"log",
"(",
"\"AutoUpdate : Exception occured in removing \"",
",",
"fileFullPath",
",",
"e",
")",
";",
"}",
"}",
"}",
")",
";",
"if",
"(",
"notifyBackToBrackets",
")",
"{",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"NOTIFY_SAFE_TO_DOWNLOAD",
",",
"currentRequester",
")",
";",
"}",
"}",
"fs",
".",
"stat",
"(",
"updateDir",
")",
".",
"then",
"(",
"function",
"(",
"stats",
")",
"{",
"if",
"(",
"stats",
")",
"{",
"if",
"(",
"filesToCache",
")",
"{",
"fs",
".",
"readdir",
"(",
"updateDir",
")",
".",
"then",
"(",
"function",
"(",
"files",
")",
"{",
"filterFilesAndNotify",
"(",
"files",
",",
"filesToCache",
",",
"notifyBack",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"\"AutoUpdate : Error in Reading Update Dir for Cleanup : \"",
"+",
"err",
".",
"toString",
"(",
")",
")",
";",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"SHOW_ERROR_MESSAGE",
",",
"currentRequester",
",",
"nodeErrorMessages",
".",
"UPDATEDIR_READ_FAILED",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"fs",
".",
"remove",
"(",
"updateDir",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"console",
".",
"log",
"(",
"'AutoUpdate : Update Directory in AppData Cleaned: Complete'",
")",
";",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"\"AutoUpdate : Error in Cleaning Update Dir : \"",
"+",
"err",
".",
"toString",
"(",
")",
")",
";",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"SHOW_ERROR_MESSAGE",
",",
"currentRequester",
",",
"nodeErrorMessages",
".",
"UPDATEDIR_CLEAN_FAILED",
")",
";",
"}",
")",
";",
"}",
"}",
"}",
")",
".",
"catch",
"(",
"function",
"(",
"err",
")",
"{",
"console",
".",
"log",
"(",
"\"AutoUpdate : Error in Reading Update Dir stats for Cleanup : \"",
"+",
"err",
".",
"toString",
"(",
")",
")",
";",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"SHOW_ERROR_MESSAGE",
",",
"currentRequester",
",",
"nodeErrorMessages",
".",
"UPDATEDIR_CLEAN_FAILED",
")",
";",
"}",
")",
";",
"}"
] |
Performs clean up for the contents in Update Directory in AppData
@param {Array} filesToCache - array of file types to cache
@param {boolean} notifyBack - true if Brackets needs to be
notified post cleanup, false otherwise
|
[
"Performs",
"clean",
"up",
"for",
"the",
"contents",
"in",
"Update",
"Directory",
"in",
"AppData"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L332-L382
|
train
|
adobe/brackets
|
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
|
initializeState
|
function initializeState(requester, updateParams) {
var currentRequester = requester || "";
_updateParams = updateParams;
installerPath = path.resolve(updateDir, updateParams.installerName);
postMessageToBrackets(MessageIds.NOTIFY_INITIALIZATION_COMPLETE, currentRequester);
}
|
javascript
|
function initializeState(requester, updateParams) {
var currentRequester = requester || "";
_updateParams = updateParams;
installerPath = path.resolve(updateDir, updateParams.installerName);
postMessageToBrackets(MessageIds.NOTIFY_INITIALIZATION_COMPLETE, currentRequester);
}
|
[
"function",
"initializeState",
"(",
"requester",
",",
"updateParams",
")",
"{",
"var",
"currentRequester",
"=",
"requester",
"||",
"\"\"",
";",
"_updateParams",
"=",
"updateParams",
";",
"installerPath",
"=",
"path",
".",
"resolve",
"(",
"updateDir",
",",
"updateParams",
".",
"installerName",
")",
";",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"NOTIFY_INITIALIZATION_COMPLETE",
",",
"currentRequester",
")",
";",
"}"
] |
Initializes the node with update parameters
@param {object} updateParams - json containing update parameters
|
[
"Initializes",
"the",
"node",
"with",
"update",
"parameters"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L388-L393
|
train
|
adobe/brackets
|
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
|
registerNodeFunctions
|
function registerNodeFunctions() {
functionMap["node.downloadInstaller"] = downloadInstaller;
functionMap["node.performCleanup"] = performCleanup;
functionMap["node.validateInstaller"] = validateChecksum;
functionMap["node.initializeState"] = initializeState;
functionMap["node.checkInstallerStatus"] = checkInstallerStatus;
functionMap["node.removeFromRequesters"] = removeFromRequesters;
}
|
javascript
|
function registerNodeFunctions() {
functionMap["node.downloadInstaller"] = downloadInstaller;
functionMap["node.performCleanup"] = performCleanup;
functionMap["node.validateInstaller"] = validateChecksum;
functionMap["node.initializeState"] = initializeState;
functionMap["node.checkInstallerStatus"] = checkInstallerStatus;
functionMap["node.removeFromRequesters"] = removeFromRequesters;
}
|
[
"function",
"registerNodeFunctions",
"(",
")",
"{",
"functionMap",
"[",
"\"node.downloadInstaller\"",
"]",
"=",
"downloadInstaller",
";",
"functionMap",
"[",
"\"node.performCleanup\"",
"]",
"=",
"performCleanup",
";",
"functionMap",
"[",
"\"node.validateInstaller\"",
"]",
"=",
"validateChecksum",
";",
"functionMap",
"[",
"\"node.initializeState\"",
"]",
"=",
"initializeState",
";",
"functionMap",
"[",
"\"node.checkInstallerStatus\"",
"]",
"=",
"checkInstallerStatus",
";",
"functionMap",
"[",
"\"node.removeFromRequesters\"",
"]",
"=",
"removeFromRequesters",
";",
"}"
] |
Generates a map for node side functions
|
[
"Generates",
"a",
"map",
"for",
"node",
"side",
"functions"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L405-L412
|
train
|
adobe/brackets
|
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
|
initNode
|
function initNode(initObj) {
var resetUpdateProgres = false;
if (!isNodeDomainInitialized) {
MessageIds = initObj.messageIds;
updateDir = path.resolve(initObj.updateDir);
logFilePath = path.resolve(updateDir, logFile);
installStatusFilePath = path.resolve(updateDir, installStatusFile);
registerNodeFunctions();
isNodeDomainInitialized = true;
resetUpdateProgres = true;
}
postMessageToBrackets(MessageIds.NODE_DOMAIN_INITIALIZED, initObj.requester.toString(), resetUpdateProgres);
requesters[initObj.requester.toString()] = true;
postMessageToBrackets(MessageIds.REGISTER_BRACKETS_FUNCTIONS, initObj.requester.toString());
}
|
javascript
|
function initNode(initObj) {
var resetUpdateProgres = false;
if (!isNodeDomainInitialized) {
MessageIds = initObj.messageIds;
updateDir = path.resolve(initObj.updateDir);
logFilePath = path.resolve(updateDir, logFile);
installStatusFilePath = path.resolve(updateDir, installStatusFile);
registerNodeFunctions();
isNodeDomainInitialized = true;
resetUpdateProgres = true;
}
postMessageToBrackets(MessageIds.NODE_DOMAIN_INITIALIZED, initObj.requester.toString(), resetUpdateProgres);
requesters[initObj.requester.toString()] = true;
postMessageToBrackets(MessageIds.REGISTER_BRACKETS_FUNCTIONS, initObj.requester.toString());
}
|
[
"function",
"initNode",
"(",
"initObj",
")",
"{",
"var",
"resetUpdateProgres",
"=",
"false",
";",
"if",
"(",
"!",
"isNodeDomainInitialized",
")",
"{",
"MessageIds",
"=",
"initObj",
".",
"messageIds",
";",
"updateDir",
"=",
"path",
".",
"resolve",
"(",
"initObj",
".",
"updateDir",
")",
";",
"logFilePath",
"=",
"path",
".",
"resolve",
"(",
"updateDir",
",",
"logFile",
")",
";",
"installStatusFilePath",
"=",
"path",
".",
"resolve",
"(",
"updateDir",
",",
"installStatusFile",
")",
";",
"registerNodeFunctions",
"(",
")",
";",
"isNodeDomainInitialized",
"=",
"true",
";",
"resetUpdateProgres",
"=",
"true",
";",
"}",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"NODE_DOMAIN_INITIALIZED",
",",
"initObj",
".",
"requester",
".",
"toString",
"(",
")",
",",
"resetUpdateProgres",
")",
";",
"requesters",
"[",
"initObj",
".",
"requester",
".",
"toString",
"(",
")",
"]",
"=",
"true",
";",
"postMessageToBrackets",
"(",
"MessageIds",
".",
"REGISTER_BRACKETS_FUNCTIONS",
",",
"initObj",
".",
"requester",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Initializes node for the auto update, registers messages and node side funtions
@param {object} initObj - json containing init information {
messageIds : Messages for brackets and node communication
updateDir : update directory in Appdata
requester : ID of the current requester domain}
|
[
"Initializes",
"node",
"for",
"the",
"auto",
"update",
"registers",
"messages",
"and",
"node",
"side",
"funtions"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L421-L435
|
train
|
adobe/brackets
|
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
|
receiveMessageFromBrackets
|
function receiveMessageFromBrackets(msgObj) {
var argList = msgObj.args;
argList.unshift(msgObj.requester || "");
functionMap[msgObj.fn].apply(null, argList);
}
|
javascript
|
function receiveMessageFromBrackets(msgObj) {
var argList = msgObj.args;
argList.unshift(msgObj.requester || "");
functionMap[msgObj.fn].apply(null, argList);
}
|
[
"function",
"receiveMessageFromBrackets",
"(",
"msgObj",
")",
"{",
"var",
"argList",
"=",
"msgObj",
".",
"args",
";",
"argList",
".",
"unshift",
"(",
"msgObj",
".",
"requester",
"||",
"\"\"",
")",
";",
"functionMap",
"[",
"msgObj",
".",
"fn",
"]",
".",
"apply",
"(",
"null",
",",
"argList",
")",
";",
"}"
] |
Receives messages from brackets
@param {object} msgObj - json containing - {
fn - function to execute on node side
args - arguments to the above function }
|
[
"Receives",
"messages",
"from",
"brackets"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L444-L448
|
train
|
adobe/brackets
|
src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js
|
init
|
function init(domainManager) {
if (!domainManager.hasDomain("AutoUpdate")) {
domainManager.registerDomain("AutoUpdate", {
major: 0,
minor: 1
});
}
_domainManager = domainManager;
domainManager.registerCommand(
"AutoUpdate",
"initNode",
initNode,
true,
"Initializes node for the auto update",
[
{
name: "initObj",
type: "object",
description: "json object containing init information"
}
],
[]
);
domainManager.registerCommand(
"AutoUpdate",
"data",
receiveMessageFromBrackets,
true,
"Receives messages from brackets",
[
{
name: "msgObj",
type: "object",
description: "json object containing message info"
}
],
[]
);
domainManager.registerEvent(
"AutoUpdate",
"data",
[
{
name: "msgObj",
type: "object",
description: "json object containing message info to pass to brackets"
}
]
);
}
|
javascript
|
function init(domainManager) {
if (!domainManager.hasDomain("AutoUpdate")) {
domainManager.registerDomain("AutoUpdate", {
major: 0,
minor: 1
});
}
_domainManager = domainManager;
domainManager.registerCommand(
"AutoUpdate",
"initNode",
initNode,
true,
"Initializes node for the auto update",
[
{
name: "initObj",
type: "object",
description: "json object containing init information"
}
],
[]
);
domainManager.registerCommand(
"AutoUpdate",
"data",
receiveMessageFromBrackets,
true,
"Receives messages from brackets",
[
{
name: "msgObj",
type: "object",
description: "json object containing message info"
}
],
[]
);
domainManager.registerEvent(
"AutoUpdate",
"data",
[
{
name: "msgObj",
type: "object",
description: "json object containing message info to pass to brackets"
}
]
);
}
|
[
"function",
"init",
"(",
"domainManager",
")",
"{",
"if",
"(",
"!",
"domainManager",
".",
"hasDomain",
"(",
"\"AutoUpdate\"",
")",
")",
"{",
"domainManager",
".",
"registerDomain",
"(",
"\"AutoUpdate\"",
",",
"{",
"major",
":",
"0",
",",
"minor",
":",
"1",
"}",
")",
";",
"}",
"_domainManager",
"=",
"domainManager",
";",
"domainManager",
".",
"registerCommand",
"(",
"\"AutoUpdate\"",
",",
"\"initNode\"",
",",
"initNode",
",",
"true",
",",
"\"Initializes node for the auto update\"",
",",
"[",
"{",
"name",
":",
"\"initObj\"",
",",
"type",
":",
"\"object\"",
",",
"description",
":",
"\"json object containing init information\"",
"}",
"]",
",",
"[",
"]",
")",
";",
"domainManager",
".",
"registerCommand",
"(",
"\"AutoUpdate\"",
",",
"\"data\"",
",",
"receiveMessageFromBrackets",
",",
"true",
",",
"\"Receives messages from brackets\"",
",",
"[",
"{",
"name",
":",
"\"msgObj\"",
",",
"type",
":",
"\"object\"",
",",
"description",
":",
"\"json object containing message info\"",
"}",
"]",
",",
"[",
"]",
")",
";",
"domainManager",
".",
"registerEvent",
"(",
"\"AutoUpdate\"",
",",
"\"data\"",
",",
"[",
"{",
"name",
":",
"\"msgObj\"",
",",
"type",
":",
"\"object\"",
",",
"description",
":",
"\"json object containing message info to pass to brackets\"",
"}",
"]",
")",
";",
"}"
] |
Initialize the domain with commands and events related to AutoUpdate
@param {DomainManager} domainManager - The DomainManager for AutoUpdateDomain
|
[
"Initialize",
"the",
"domain",
"with",
"commands",
"and",
"events",
"related",
"to",
"AutoUpdate"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/extensions/default/AutoUpdate/node/AutoUpdateDomain.js#L455-L507
|
train
|
adobe/brackets
|
src/editor/Editor.js
|
_buildPreferencesContext
|
function _buildPreferencesContext(fullPath) {
return PreferencesManager._buildContext(fullPath,
fullPath ? LanguageManager.getLanguageForPath(fullPath).getId() : undefined);
}
|
javascript
|
function _buildPreferencesContext(fullPath) {
return PreferencesManager._buildContext(fullPath,
fullPath ? LanguageManager.getLanguageForPath(fullPath).getId() : undefined);
}
|
[
"function",
"_buildPreferencesContext",
"(",
"fullPath",
")",
"{",
"return",
"PreferencesManager",
".",
"_buildContext",
"(",
"fullPath",
",",
"fullPath",
"?",
"LanguageManager",
".",
"getLanguageForPath",
"(",
"fullPath",
")",
".",
"getId",
"(",
")",
":",
"undefined",
")",
";",
"}"
] |
Helper function to build preferences context based on the full path of
the file.
@param {string} fullPath Full path of the file
@return {*} A context for the specified file name
|
[
"Helper",
"function",
"to",
"build",
"preferences",
"context",
"based",
"on",
"the",
"full",
"path",
"of",
"the",
"file",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/Editor.js#L292-L295
|
train
|
adobe/brackets
|
src/editor/Editor.js
|
_onKeyEvent
|
function _onKeyEvent(instance, event) {
self.trigger("keyEvent", self, event); // deprecated
self.trigger(event.type, self, event);
return event.defaultPrevented; // false tells CodeMirror we didn't eat the event
}
|
javascript
|
function _onKeyEvent(instance, event) {
self.trigger("keyEvent", self, event); // deprecated
self.trigger(event.type, self, event);
return event.defaultPrevented; // false tells CodeMirror we didn't eat the event
}
|
[
"function",
"_onKeyEvent",
"(",
"instance",
",",
"event",
")",
"{",
"self",
".",
"trigger",
"(",
"\"keyEvent\"",
",",
"self",
",",
"event",
")",
";",
"self",
".",
"trigger",
"(",
"event",
".",
"type",
",",
"self",
",",
"event",
")",
";",
"return",
"event",
".",
"defaultPrevented",
";",
"}"
] |
Redispatch these CodeMirror key events as Editor events
|
[
"Redispatch",
"these",
"CodeMirror",
"key",
"events",
"as",
"Editor",
"events"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/editor/Editor.js#L1004-L1008
|
train
|
adobe/brackets
|
src/utils/StringUtils.js
|
format
|
function format(str) {
// arguments[0] is the base string, so we need to adjust index values here
var args = [].slice.call(arguments, 1);
return str.replace(/\{(\d+)\}/g, function (match, num) {
return typeof args[num] !== "undefined" ? args[num] : match;
});
}
|
javascript
|
function format(str) {
// arguments[0] is the base string, so we need to adjust index values here
var args = [].slice.call(arguments, 1);
return str.replace(/\{(\d+)\}/g, function (match, num) {
return typeof args[num] !== "undefined" ? args[num] : match;
});
}
|
[
"function",
"format",
"(",
"str",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
",",
"1",
")",
";",
"return",
"str",
".",
"replace",
"(",
"/",
"\\{(\\d+)\\}",
"/",
"g",
",",
"function",
"(",
"match",
",",
"num",
")",
"{",
"return",
"typeof",
"args",
"[",
"num",
"]",
"!==",
"\"undefined\"",
"?",
"args",
"[",
"num",
"]",
":",
"match",
";",
"}",
")",
";",
"}"
] |
Format a string by replacing placeholder symbols with passed in arguments.
Example: var formatted = StringUtils.format("Hello {0}", "World");
@param {string} str The base string
@param {...} Arguments to be substituted into the string
@return {string} Formatted string
|
[
"Format",
"a",
"string",
"by",
"replacing",
"placeholder",
"symbols",
"with",
"passed",
"in",
"arguments",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/StringUtils.js#L50-L56
|
train
|
adobe/brackets
|
src/utils/StringUtils.js
|
breakableUrl
|
function breakableUrl(url) {
// This is for displaying in UI, so always want it escaped
var escUrl = _.escape(url);
// Inject zero-width space character (U+200B) near path separators (/) to allow line breaking there
return escUrl.replace(
new RegExp(regexEscape("/"), "g"),
"/" + "​"
);
}
|
javascript
|
function breakableUrl(url) {
// This is for displaying in UI, so always want it escaped
var escUrl = _.escape(url);
// Inject zero-width space character (U+200B) near path separators (/) to allow line breaking there
return escUrl.replace(
new RegExp(regexEscape("/"), "g"),
"/" + "​"
);
}
|
[
"function",
"breakableUrl",
"(",
"url",
")",
"{",
"var",
"escUrl",
"=",
"_",
".",
"escape",
"(",
"url",
")",
";",
"return",
"escUrl",
".",
"replace",
"(",
"new",
"RegExp",
"(",
"regexEscape",
"(",
"\"/\"",
")",
",",
"\"g\"",
")",
",",
"\"/\"",
"+",
"\"​\"",
")",
";",
"}"
] |
Return an escaped path or URL string that can be broken near path separators.
@param {string} url the path or URL to format
@return {string} the formatted path or URL
|
[
"Return",
"an",
"escaped",
"path",
"or",
"URL",
"string",
"that",
"can",
"be",
"broken",
"near",
"path",
"separators",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/StringUtils.js#L166-L175
|
train
|
adobe/brackets
|
src/utils/StringUtils.js
|
prettyPrintBytes
|
function prettyPrintBytes(bytes, precision) {
var kilobyte = 1024,
megabyte = kilobyte * 1024,
gigabyte = megabyte * 1024,
terabyte = gigabyte * 1024,
returnVal = bytes;
if ((bytes >= 0) && (bytes < kilobyte)) {
returnVal = bytes + " B";
} else if (bytes < megabyte) {
returnVal = (bytes / kilobyte).toFixed(precision) + " KB";
} else if (bytes < gigabyte) {
returnVal = (bytes / megabyte).toFixed(precision) + " MB";
} else if (bytes < terabyte) {
returnVal = (bytes / gigabyte).toFixed(precision) + " GB";
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + " TB";
}
return returnVal;
}
|
javascript
|
function prettyPrintBytes(bytes, precision) {
var kilobyte = 1024,
megabyte = kilobyte * 1024,
gigabyte = megabyte * 1024,
terabyte = gigabyte * 1024,
returnVal = bytes;
if ((bytes >= 0) && (bytes < kilobyte)) {
returnVal = bytes + " B";
} else if (bytes < megabyte) {
returnVal = (bytes / kilobyte).toFixed(precision) + " KB";
} else if (bytes < gigabyte) {
returnVal = (bytes / megabyte).toFixed(precision) + " MB";
} else if (bytes < terabyte) {
returnVal = (bytes / gigabyte).toFixed(precision) + " GB";
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + " TB";
}
return returnVal;
}
|
[
"function",
"prettyPrintBytes",
"(",
"bytes",
",",
"precision",
")",
"{",
"var",
"kilobyte",
"=",
"1024",
",",
"megabyte",
"=",
"kilobyte",
"*",
"1024",
",",
"gigabyte",
"=",
"megabyte",
"*",
"1024",
",",
"terabyte",
"=",
"gigabyte",
"*",
"1024",
",",
"returnVal",
"=",
"bytes",
";",
"if",
"(",
"(",
"bytes",
">=",
"0",
")",
"&&",
"(",
"bytes",
"<",
"kilobyte",
")",
")",
"{",
"returnVal",
"=",
"bytes",
"+",
"\" B\"",
";",
"}",
"else",
"if",
"(",
"bytes",
"<",
"megabyte",
")",
"{",
"returnVal",
"=",
"(",
"bytes",
"/",
"kilobyte",
")",
".",
"toFixed",
"(",
"precision",
")",
"+",
"\" KB\"",
";",
"}",
"else",
"if",
"(",
"bytes",
"<",
"gigabyte",
")",
"{",
"returnVal",
"=",
"(",
"bytes",
"/",
"megabyte",
")",
".",
"toFixed",
"(",
"precision",
")",
"+",
"\" MB\"",
";",
"}",
"else",
"if",
"(",
"bytes",
"<",
"terabyte",
")",
"{",
"returnVal",
"=",
"(",
"bytes",
"/",
"gigabyte",
")",
".",
"toFixed",
"(",
"precision",
")",
"+",
"\" GB\"",
";",
"}",
"else",
"if",
"(",
"bytes",
">=",
"terabyte",
")",
"{",
"return",
"(",
"bytes",
"/",
"terabyte",
")",
".",
"toFixed",
"(",
"precision",
")",
"+",
"\" TB\"",
";",
"}",
"return",
"returnVal",
";",
"}"
] |
Converts number of bytes into human readable format.
If param bytes is negative it returns the number without any changes.
@param {number} bytes Number of bytes to convert
@param {number} precision Number of digits after the decimal separator
@return {string}
|
[
"Converts",
"number",
"of",
"bytes",
"into",
"human",
"readable",
"format",
".",
"If",
"param",
"bytes",
"is",
"negative",
"it",
"returns",
"the",
"number",
"without",
"any",
"changes",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/StringUtils.js#L185-L205
|
train
|
adobe/brackets
|
src/utils/StringUtils.js
|
truncate
|
function truncate(str, len) {
// Truncate text to specified length
if (str.length > len) {
str = str.substr(0, len);
// To prevent awkwardly truncating in the middle of a word,
// attempt to truncate at the end of the last whole word
var lastSpaceChar = str.lastIndexOf(" ");
if (lastSpaceChar < len && lastSpaceChar > -1) {
str = str.substr(0, lastSpaceChar);
}
return str;
}
}
|
javascript
|
function truncate(str, len) {
// Truncate text to specified length
if (str.length > len) {
str = str.substr(0, len);
// To prevent awkwardly truncating in the middle of a word,
// attempt to truncate at the end of the last whole word
var lastSpaceChar = str.lastIndexOf(" ");
if (lastSpaceChar < len && lastSpaceChar > -1) {
str = str.substr(0, lastSpaceChar);
}
return str;
}
}
|
[
"function",
"truncate",
"(",
"str",
",",
"len",
")",
"{",
"if",
"(",
"str",
".",
"length",
">",
"len",
")",
"{",
"str",
"=",
"str",
".",
"substr",
"(",
"0",
",",
"len",
")",
";",
"var",
"lastSpaceChar",
"=",
"str",
".",
"lastIndexOf",
"(",
"\" \"",
")",
";",
"if",
"(",
"lastSpaceChar",
"<",
"len",
"&&",
"lastSpaceChar",
">",
"-",
"1",
")",
"{",
"str",
"=",
"str",
".",
"substr",
"(",
"0",
",",
"lastSpaceChar",
")",
";",
"}",
"return",
"str",
";",
"}",
"}"
] |
Truncate text to specified length.
@param {string} str Text to be truncated.
@param {number} len Length to which text should be truncated
@return {?string} Returns truncated text only if it was changed
|
[
"Truncate",
"text",
"to",
"specified",
"length",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/StringUtils.js#L213-L226
|
train
|
adobe/brackets
|
src/utils/ValidationUtils.js
|
isInteger
|
function isInteger(value) {
// Validate value is a number
if (typeof (value) !== "number" || isNaN(parseInt(value, 10))) {
return false;
}
// Validate number is an integer
if (Math.floor(value) !== value) {
return false;
}
// Validate number is finite
if (!isFinite(value)) {
return false;
}
return true;
}
|
javascript
|
function isInteger(value) {
// Validate value is a number
if (typeof (value) !== "number" || isNaN(parseInt(value, 10))) {
return false;
}
// Validate number is an integer
if (Math.floor(value) !== value) {
return false;
}
// Validate number is finite
if (!isFinite(value)) {
return false;
}
return true;
}
|
[
"function",
"isInteger",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"(",
"value",
")",
"!==",
"\"number\"",
"||",
"isNaN",
"(",
"parseInt",
"(",
"value",
",",
"10",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"Math",
".",
"floor",
"(",
"value",
")",
"!==",
"value",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"isFinite",
"(",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Used to validate whether type of unknown value is an integer.
@param {*} value Value for which to validate its type
@return {boolean} true if value is a finite integer
|
[
"Used",
"to",
"validate",
"whether",
"type",
"of",
"unknown",
"value",
"is",
"an",
"integer",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ValidationUtils.js#L34-L51
|
train
|
adobe/brackets
|
src/utils/ValidationUtils.js
|
isIntegerInRange
|
function isIntegerInRange(value, lowerLimit, upperLimit) {
// Validate value is an integer
if (!isInteger(value)) {
return false;
}
// Validate integer is in range
var hasLowerLimt = (typeof (lowerLimit) === "number"),
hasUpperLimt = (typeof (upperLimit) === "number");
return ((!hasLowerLimt || value >= lowerLimit) && (!hasUpperLimt || value <= upperLimit));
}
|
javascript
|
function isIntegerInRange(value, lowerLimit, upperLimit) {
// Validate value is an integer
if (!isInteger(value)) {
return false;
}
// Validate integer is in range
var hasLowerLimt = (typeof (lowerLimit) === "number"),
hasUpperLimt = (typeof (upperLimit) === "number");
return ((!hasLowerLimt || value >= lowerLimit) && (!hasUpperLimt || value <= upperLimit));
}
|
[
"function",
"isIntegerInRange",
"(",
"value",
",",
"lowerLimit",
",",
"upperLimit",
")",
"{",
"if",
"(",
"!",
"isInteger",
"(",
"value",
")",
")",
"{",
"return",
"false",
";",
"}",
"var",
"hasLowerLimt",
"=",
"(",
"typeof",
"(",
"lowerLimit",
")",
"===",
"\"number\"",
")",
",",
"hasUpperLimt",
"=",
"(",
"typeof",
"(",
"upperLimit",
")",
"===",
"\"number\"",
")",
";",
"return",
"(",
"(",
"!",
"hasLowerLimt",
"||",
"value",
">=",
"lowerLimit",
")",
"&&",
"(",
"!",
"hasUpperLimt",
"||",
"value",
"<=",
"upperLimit",
")",
")",
";",
"}"
] |
Used to validate whether type of unknown value is an integer, and, if so,
is it within the option lower and upper limits.
@param {*} value Value for which to validate its type
@param {number=} lowerLimit Optional lower limit (inclusive)
@param {number=} upperLimit Optional upper limit (inclusive)
@return {boolean} true if value is an interger, and optionally in specified range.
|
[
"Used",
"to",
"validate",
"whether",
"type",
"of",
"unknown",
"value",
"is",
"an",
"integer",
"and",
"if",
"so",
"is",
"it",
"within",
"the",
"option",
"lower",
"and",
"upper",
"limits",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/utils/ValidationUtils.js#L62-L73
|
train
|
adobe/brackets
|
src/document/TextRange.js
|
TextRange
|
function TextRange(document, startLine, endLine) {
this.startLine = startLine;
this.endLine = endLine;
this.document = document;
document.addRef();
// store this-bound versions of listeners so we can remove them later
this._handleDocumentChange = this._handleDocumentChange.bind(this);
this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this);
document.on("change", this._handleDocumentChange);
document.on("deleted", this._handleDocumentDeleted);
}
|
javascript
|
function TextRange(document, startLine, endLine) {
this.startLine = startLine;
this.endLine = endLine;
this.document = document;
document.addRef();
// store this-bound versions of listeners so we can remove them later
this._handleDocumentChange = this._handleDocumentChange.bind(this);
this._handleDocumentDeleted = this._handleDocumentDeleted.bind(this);
document.on("change", this._handleDocumentChange);
document.on("deleted", this._handleDocumentDeleted);
}
|
[
"function",
"TextRange",
"(",
"document",
",",
"startLine",
",",
"endLine",
")",
"{",
"this",
".",
"startLine",
"=",
"startLine",
";",
"this",
".",
"endLine",
"=",
"endLine",
";",
"this",
".",
"document",
"=",
"document",
";",
"document",
".",
"addRef",
"(",
")",
";",
"this",
".",
"_handleDocumentChange",
"=",
"this",
".",
"_handleDocumentChange",
".",
"bind",
"(",
"this",
")",
";",
"this",
".",
"_handleDocumentDeleted",
"=",
"this",
".",
"_handleDocumentDeleted",
".",
"bind",
"(",
"this",
")",
";",
"document",
".",
"on",
"(",
"\"change\"",
",",
"this",
".",
"_handleDocumentChange",
")",
";",
"document",
".",
"on",
"(",
"\"deleted\"",
",",
"this",
".",
"_handleDocumentDeleted",
")",
";",
"}"
] |
Stores a range of lines that is automatically maintained as the Document changes. The range
MAY drop out of sync with the Document in certain edge cases; startLine & endLine will become
null when that happens.
Important: you must dispose() a TextRange when you're done with it. Because TextRange addRef()s
the Document (in order to listen to it), you will leak Documents otherwise.
TextRange dispatches these events:
- change -- When the range boundary line numbers change (due to a Document change)
- contentChange -- When the actual content of the range changes. This might or might not
be accompanied by a change in the boundary line numbers.
- lostSync -- When the backing Document changes in such a way that the range can no longer
accurately be maintained. Generally, occurs whenever an edit spans a range boundary.
After this, startLine & endLine will be unusable (set to null).
Also occurs when the document is deleted, though startLine & endLine won't be modified
These events only ever occur in response to Document changes, so if you are already listening
to the Document, you could ignore the TextRange events and just read its updated value in your
own Document change handler.
@constructor
@param {!Document} document
@param {number} startLine First line in range (0-based, inclusive)
@param {number} endLine Last line in range (0-based, inclusive)
|
[
"Stores",
"a",
"range",
"of",
"lines",
"that",
"is",
"automatically",
"maintained",
"as",
"the",
"Document",
"changes",
".",
"The",
"range",
"MAY",
"drop",
"out",
"of",
"sync",
"with",
"the",
"Document",
"in",
"certain",
"edge",
"cases",
";",
"startLine",
"&",
"endLine",
"will",
"become",
"null",
"when",
"that",
"happens",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/document/TextRange.js#L58-L69
|
train
|
adobe/brackets
|
src/language/CSSUtils.js
|
getInfoAtPos
|
function getInfoAtPos(editor, constPos) {
// We're going to be changing pos a lot, but we don't want to mess up
// the pos the caller passed in so we use extend to make a safe copy of it.
var pos = $.extend({}, constPos),
ctx = TokenUtils.getInitialContext(editor._codeMirror, pos),
mode = editor.getModeForSelection();
// Check if this is inside a style block or in a css/less document.
if (mode !== "css" && mode !== "text/x-scss" && mode !== "text/x-less") {
return createInfo();
}
// Context from the current editor will have htmlState if we are in css mode
// and in attribute value state of a tag with attribute name style
if (ctx.token.state.htmlState && (!ctx.token.state.localMode || ctx.token.state.localMode.name !== "css")) {
// tagInfo is required to aquire the style attr value
var tagInfo = HTMLUtils.getTagInfo(editor, pos, true),
// To be used as relative character position
offset = tagInfo.position.offset;
/**
* We will use this CM to cook css context in case of style attribute value
* as CM in htmlmixed mode doesn't yet identify this as css context. We provide
* a no-op display function to run CM without a DOM head.
*/
var _contextCM = new CodeMirror(function () {}, {
value: "{" + tagInfo.attr.value.replace(/(^")|("$)/g, ""),
mode: "css"
});
ctx = TokenUtils.getInitialContext(_contextCM, {line: 0, ch: offset + 1});
}
if (_isInPropName(ctx)) {
return _getPropNameInfo(ctx);
}
if (_isInPropValue(ctx)) {
return _getRuleInfoStartingFromPropValue(ctx, ctx.editor);
}
if (_isInAtRule(ctx)) {
return _getImportUrlInfo(ctx, editor);
}
return createInfo();
}
|
javascript
|
function getInfoAtPos(editor, constPos) {
// We're going to be changing pos a lot, but we don't want to mess up
// the pos the caller passed in so we use extend to make a safe copy of it.
var pos = $.extend({}, constPos),
ctx = TokenUtils.getInitialContext(editor._codeMirror, pos),
mode = editor.getModeForSelection();
// Check if this is inside a style block or in a css/less document.
if (mode !== "css" && mode !== "text/x-scss" && mode !== "text/x-less") {
return createInfo();
}
// Context from the current editor will have htmlState if we are in css mode
// and in attribute value state of a tag with attribute name style
if (ctx.token.state.htmlState && (!ctx.token.state.localMode || ctx.token.state.localMode.name !== "css")) {
// tagInfo is required to aquire the style attr value
var tagInfo = HTMLUtils.getTagInfo(editor, pos, true),
// To be used as relative character position
offset = tagInfo.position.offset;
/**
* We will use this CM to cook css context in case of style attribute value
* as CM in htmlmixed mode doesn't yet identify this as css context. We provide
* a no-op display function to run CM without a DOM head.
*/
var _contextCM = new CodeMirror(function () {}, {
value: "{" + tagInfo.attr.value.replace(/(^")|("$)/g, ""),
mode: "css"
});
ctx = TokenUtils.getInitialContext(_contextCM, {line: 0, ch: offset + 1});
}
if (_isInPropName(ctx)) {
return _getPropNameInfo(ctx);
}
if (_isInPropValue(ctx)) {
return _getRuleInfoStartingFromPropValue(ctx, ctx.editor);
}
if (_isInAtRule(ctx)) {
return _getImportUrlInfo(ctx, editor);
}
return createInfo();
}
|
[
"function",
"getInfoAtPos",
"(",
"editor",
",",
"constPos",
")",
"{",
"var",
"pos",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"constPos",
")",
",",
"ctx",
"=",
"TokenUtils",
".",
"getInitialContext",
"(",
"editor",
".",
"_codeMirror",
",",
"pos",
")",
",",
"mode",
"=",
"editor",
".",
"getModeForSelection",
"(",
")",
";",
"if",
"(",
"mode",
"!==",
"\"css\"",
"&&",
"mode",
"!==",
"\"text/x-scss\"",
"&&",
"mode",
"!==",
"\"text/x-less\"",
")",
"{",
"return",
"createInfo",
"(",
")",
";",
"}",
"if",
"(",
"ctx",
".",
"token",
".",
"state",
".",
"htmlState",
"&&",
"(",
"!",
"ctx",
".",
"token",
".",
"state",
".",
"localMode",
"||",
"ctx",
".",
"token",
".",
"state",
".",
"localMode",
".",
"name",
"!==",
"\"css\"",
")",
")",
"{",
"var",
"tagInfo",
"=",
"HTMLUtils",
".",
"getTagInfo",
"(",
"editor",
",",
"pos",
",",
"true",
")",
",",
"offset",
"=",
"tagInfo",
".",
"position",
".",
"offset",
";",
"var",
"_contextCM",
"=",
"new",
"CodeMirror",
"(",
"function",
"(",
")",
"{",
"}",
",",
"{",
"value",
":",
"\"{\"",
"+",
"tagInfo",
".",
"attr",
".",
"value",
".",
"replace",
"(",
"/",
"(^\")|(\"$)",
"/",
"g",
",",
"\"\"",
")",
",",
"mode",
":",
"\"css\"",
"}",
")",
";",
"ctx",
"=",
"TokenUtils",
".",
"getInitialContext",
"(",
"_contextCM",
",",
"{",
"line",
":",
"0",
",",
"ch",
":",
"offset",
"+",
"1",
"}",
")",
";",
"}",
"if",
"(",
"_isInPropName",
"(",
"ctx",
")",
")",
"{",
"return",
"_getPropNameInfo",
"(",
"ctx",
")",
";",
"}",
"if",
"(",
"_isInPropValue",
"(",
"ctx",
")",
")",
"{",
"return",
"_getRuleInfoStartingFromPropValue",
"(",
"ctx",
",",
"ctx",
".",
"editor",
")",
";",
"}",
"if",
"(",
"_isInAtRule",
"(",
"ctx",
")",
")",
"{",
"return",
"_getImportUrlInfo",
"(",
"ctx",
",",
"editor",
")",
";",
"}",
"return",
"createInfo",
"(",
")",
";",
"}"
] |
Returns a context info object for the given cursor position
@param {!Editor} editor
@param {{ch: number, line: number}} constPos A CM pos (likely from editor.getCursorPos())
@return {{context: string,
offset: number,
name: string,
index: number,
values: Array.<string>,
isNewItem: boolean,
range: {start: {line: number, ch: number},
end: {line: number, ch: number}}}} A CSS context info object.
|
[
"Returns",
"a",
"context",
"info",
"object",
"for",
"the",
"given",
"cursor",
"position"
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/language/CSSUtils.js#L611-L658
|
train
|
adobe/brackets
|
src/language/CSSUtils.js
|
getCompleteSelectors
|
function getCompleteSelectors(info, useGroup) {
if (info.parentSelectors) {
// Show parents with / separators.
var completeSelectors = info.parentSelectors + " / ";
if (useGroup && info.selectorGroup) {
completeSelectors += info.selectorGroup;
} else {
completeSelectors += info.selector;
}
return completeSelectors;
} else if (useGroup && info.selectorGroup) {
return info.selectorGroup;
}
return info.selector;
}
|
javascript
|
function getCompleteSelectors(info, useGroup) {
if (info.parentSelectors) {
// Show parents with / separators.
var completeSelectors = info.parentSelectors + " / ";
if (useGroup && info.selectorGroup) {
completeSelectors += info.selectorGroup;
} else {
completeSelectors += info.selector;
}
return completeSelectors;
} else if (useGroup && info.selectorGroup) {
return info.selectorGroup;
}
return info.selector;
}
|
[
"function",
"getCompleteSelectors",
"(",
"info",
",",
"useGroup",
")",
"{",
"if",
"(",
"info",
".",
"parentSelectors",
")",
"{",
"var",
"completeSelectors",
"=",
"info",
".",
"parentSelectors",
"+",
"\" / \"",
";",
"if",
"(",
"useGroup",
"&&",
"info",
".",
"selectorGroup",
")",
"{",
"completeSelectors",
"+=",
"info",
".",
"selectorGroup",
";",
"}",
"else",
"{",
"completeSelectors",
"+=",
"info",
".",
"selector",
";",
"}",
"return",
"completeSelectors",
";",
"}",
"else",
"if",
"(",
"useGroup",
"&&",
"info",
".",
"selectorGroup",
")",
"{",
"return",
"info",
".",
"selectorGroup",
";",
"}",
"return",
"info",
".",
"selector",
";",
"}"
] |
Return a string that shows the literal parent hierarchy of the selector
in info.
@param {!SelectorInfo} info
@param {boolean=} useGroup true to append selectorGroup instead of selector
@return {string} the literal parent hierarchy of the selector
|
[
"Return",
"a",
"string",
"that",
"shows",
"the",
"literal",
"parent",
"hierarchy",
"of",
"the",
"selector",
"in",
"info",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/language/CSSUtils.js#L668-L683
|
train
|
adobe/brackets
|
src/language/CSSUtils.js
|
_getSelectorInFinalCSSForm
|
function _getSelectorInFinalCSSForm(selectorArray) {
var finalSelectorArray = [""],
parentSelectorArray = [],
group = [];
_.forEach(selectorArray, function (selector) {
selector = _stripAtRules(selector);
group = selector.split(",");
parentSelectorArray = [];
_.forEach(group, function (cs) {
var ampersandIndex = cs.indexOf("&");
_.forEach(finalSelectorArray, function (ps) {
if (ampersandIndex === -1) {
cs = _stripAtRules(cs);
if (ps.length && cs.length) {
ps += " ";
}
ps += cs;
} else {
// Replace all instances of & with regexp
ps = _stripAtRules(cs.replace(/&/g, ps));
}
parentSelectorArray.push(ps);
});
});
finalSelectorArray = parentSelectorArray;
});
return finalSelectorArray.join(", ");
}
|
javascript
|
function _getSelectorInFinalCSSForm(selectorArray) {
var finalSelectorArray = [""],
parentSelectorArray = [],
group = [];
_.forEach(selectorArray, function (selector) {
selector = _stripAtRules(selector);
group = selector.split(",");
parentSelectorArray = [];
_.forEach(group, function (cs) {
var ampersandIndex = cs.indexOf("&");
_.forEach(finalSelectorArray, function (ps) {
if (ampersandIndex === -1) {
cs = _stripAtRules(cs);
if (ps.length && cs.length) {
ps += " ";
}
ps += cs;
} else {
// Replace all instances of & with regexp
ps = _stripAtRules(cs.replace(/&/g, ps));
}
parentSelectorArray.push(ps);
});
});
finalSelectorArray = parentSelectorArray;
});
return finalSelectorArray.join(", ");
}
|
[
"function",
"_getSelectorInFinalCSSForm",
"(",
"selectorArray",
")",
"{",
"var",
"finalSelectorArray",
"=",
"[",
"\"\"",
"]",
",",
"parentSelectorArray",
"=",
"[",
"]",
",",
"group",
"=",
"[",
"]",
";",
"_",
".",
"forEach",
"(",
"selectorArray",
",",
"function",
"(",
"selector",
")",
"{",
"selector",
"=",
"_stripAtRules",
"(",
"selector",
")",
";",
"group",
"=",
"selector",
".",
"split",
"(",
"\",\"",
")",
";",
"parentSelectorArray",
"=",
"[",
"]",
";",
"_",
".",
"forEach",
"(",
"group",
",",
"function",
"(",
"cs",
")",
"{",
"var",
"ampersandIndex",
"=",
"cs",
".",
"indexOf",
"(",
"\"&\"",
")",
";",
"_",
".",
"forEach",
"(",
"finalSelectorArray",
",",
"function",
"(",
"ps",
")",
"{",
"if",
"(",
"ampersandIndex",
"===",
"-",
"1",
")",
"{",
"cs",
"=",
"_stripAtRules",
"(",
"cs",
")",
";",
"if",
"(",
"ps",
".",
"length",
"&&",
"cs",
".",
"length",
")",
"{",
"ps",
"+=",
"\" \"",
";",
"}",
"ps",
"+=",
"cs",
";",
"}",
"else",
"{",
"ps",
"=",
"_stripAtRules",
"(",
"cs",
".",
"replace",
"(",
"/",
"&",
"/",
"g",
",",
"ps",
")",
")",
";",
"}",
"parentSelectorArray",
".",
"push",
"(",
"ps",
")",
";",
"}",
")",
";",
"}",
")",
";",
"finalSelectorArray",
"=",
"parentSelectorArray",
";",
"}",
")",
";",
"return",
"finalSelectorArray",
".",
"join",
"(",
"\", \"",
")",
";",
"}"
] |
Converts the given selector array into the actual CSS selectors similar to
those generated by a CSS preprocessor.
@param {Array.<string>} selectorArray
@return {string}
|
[
"Converts",
"the",
"given",
"selector",
"array",
"into",
"the",
"actual",
"CSS",
"selectors",
"similar",
"to",
"those",
"generated",
"by",
"a",
"CSS",
"preprocessor",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/language/CSSUtils.js#L1314-L1341
|
train
|
adobe/brackets
|
src/language/CSSUtils.js
|
_findAllMatchingSelectorsInText
|
function _findAllMatchingSelectorsInText(text, selector, mode) {
var allSelectors = extractAllSelectors(text, mode);
var result = [];
// For now, we only match the rightmost simple selector, and ignore
// attribute selectors and pseudo selectors
var classOrIdSelector = selector[0] === "." || selector[0] === "#";
// Escape initial "." in selector, if present.
if (selector[0] === ".") {
selector = "\\" + selector;
}
if (!classOrIdSelector) {
// Tag selectors must have nothing, whitespace, or a combinator before it.
selector = "(^|[\\s>+~])" + selector;
}
var re = new RegExp(selector + "(\\[[^\\]]*\\]|:{1,2}[\\w-()]+|\\.[\\w-]+|#[\\w-]+)*\\s*$", classOrIdSelector ? "" : "i");
allSelectors.forEach(function (entry) {
var actualSelector = entry.selector;
if (entry.selector.indexOf("&") !== -1 && entry.parentSelectors) {
var selectorArray = entry.parentSelectors.split(" / ");
selectorArray.push(entry.selector);
actualSelector = _getSelectorInFinalCSSForm(selectorArray);
}
if (actualSelector.search(re) !== -1) {
result.push(entry);
} else if (!classOrIdSelector) {
// Special case for tag selectors - match "*" as the rightmost character
if (/\*\s*$/.test(actualSelector)) {
result.push(entry);
}
}
});
return result;
}
|
javascript
|
function _findAllMatchingSelectorsInText(text, selector, mode) {
var allSelectors = extractAllSelectors(text, mode);
var result = [];
// For now, we only match the rightmost simple selector, and ignore
// attribute selectors and pseudo selectors
var classOrIdSelector = selector[0] === "." || selector[0] === "#";
// Escape initial "." in selector, if present.
if (selector[0] === ".") {
selector = "\\" + selector;
}
if (!classOrIdSelector) {
// Tag selectors must have nothing, whitespace, or a combinator before it.
selector = "(^|[\\s>+~])" + selector;
}
var re = new RegExp(selector + "(\\[[^\\]]*\\]|:{1,2}[\\w-()]+|\\.[\\w-]+|#[\\w-]+)*\\s*$", classOrIdSelector ? "" : "i");
allSelectors.forEach(function (entry) {
var actualSelector = entry.selector;
if (entry.selector.indexOf("&") !== -1 && entry.parentSelectors) {
var selectorArray = entry.parentSelectors.split(" / ");
selectorArray.push(entry.selector);
actualSelector = _getSelectorInFinalCSSForm(selectorArray);
}
if (actualSelector.search(re) !== -1) {
result.push(entry);
} else if (!classOrIdSelector) {
// Special case for tag selectors - match "*" as the rightmost character
if (/\*\s*$/.test(actualSelector)) {
result.push(entry);
}
}
});
return result;
}
|
[
"function",
"_findAllMatchingSelectorsInText",
"(",
"text",
",",
"selector",
",",
"mode",
")",
"{",
"var",
"allSelectors",
"=",
"extractAllSelectors",
"(",
"text",
",",
"mode",
")",
";",
"var",
"result",
"=",
"[",
"]",
";",
"var",
"classOrIdSelector",
"=",
"selector",
"[",
"0",
"]",
"===",
"\".\"",
"||",
"selector",
"[",
"0",
"]",
"===",
"\"#\"",
";",
"if",
"(",
"selector",
"[",
"0",
"]",
"===",
"\".\"",
")",
"{",
"selector",
"=",
"\"\\\\\"",
"+",
"\\\\",
";",
"}",
"selector",
"if",
"(",
"!",
"classOrIdSelector",
")",
"{",
"selector",
"=",
"\"(^|[\\\\s>+~])\"",
"+",
"\\\\",
";",
"}",
"selector",
"var",
"re",
"=",
"new",
"RegExp",
"(",
"selector",
"+",
"\"(\\\\[[^\\\\]]*\\\\]|:{1,2}[\\\\w-()]+|\\\\.[\\\\w-]+|#[\\\\w-]+)*\\\\s*$\"",
",",
"\\\\",
")",
";",
"}"
] |
Finds all instances of the specified selector in "text".
Returns an Array of Objects with start and end properties.
For now, we only support simple selectors. This function will need to change
dramatically to support full selectors.
FUTURE: (JRB) It would be nice to eventually use the browser/jquery to do the selector evaluation.
One way to do this would be to take the user's HTML, add a special attribute to every tag with a UID,
and then construct a DOM (using the commented out code above). Then, give this DOM and the selector to
jquery and ask what matches. If the node that the user's cursor is in comes back from jquery, then
we know the selector applies.
@param {!string} text CSS text to search
@param {!string} selector selector to search for
@param {!string} mode language mode of the document that text belongs to
@return {Array.<{selectorGroupStartLine:number, declListEndLine:number, selector:string}>}
Array of objects containing the start and end line numbers (0-based, inclusive range) for each
matched selector.
|
[
"Finds",
"all",
"instances",
"of",
"the",
"specified",
"selector",
"in",
"text",
".",
"Returns",
"an",
"Array",
"of",
"Objects",
"with",
"start",
"and",
"end",
"properties",
"."
] |
d5d00d43602c438266d32b8eda8f8a3ca937b524
|
https://github.com/adobe/brackets/blob/d5d00d43602c438266d32b8eda8f8a3ca937b524/src/language/CSSUtils.js#L1363-L1400
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.