_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q16800
getFile
train
function getFile(name, next) { // save the callback fileCallBacks[name] = next; setImmediate(function () { try { ExtractContent.extractContent(name, handleGetFile, _requestFileContent); } catch (error) { console.log(error); } }); }
javascript
{ "resource": "" }
q16801
resetTernServer
train
function resetTernServer() { // If a server is already created just reset the analysis data if (ternServer) { ternServer.reset(); Infer.resetGuessing(); // tell the main thread we're ready to start processing again self.postMessage({type: MessageIds.TERN_WORKER_READY}); } }
javascript
{ "resource": "" }
q16802
buildRequest
train
function buildRequest(fileInfo, query, offset) { query = {type: query}; query.start = offset; query.end = offset; query.file = (fileInfo.type === MessageIds.TERN_FILE_INFO_TYPE_PART) ? "#0" : fileInfo.name; query.filter = false; query.sort = false; query.depths = true; query.guess = true; query.origins = true; query.types = true; query.expandWordForward = false; query.lineCharPositions = true; query.docs = true; query.urls = true; var request = {query: query, files: [], offset: offset, timeout: inferenceTimeout}; if (fileInfo.type !== MessageIds.TERN_FILE_INFO_TYPE_EMPTY) { // Create a copy to mutate ahead var fileInfoCopy = JSON.parse(JSON.stringify(fileInfo)); request.files.push(fileInfoCopy); } return request; }
javascript
{ "resource": "" }
q16803
getRefs
train
function getRefs(fileInfo, offset) { var request = buildRequest(fileInfo, "refs", offset); try { ternServer.request(request, function (error, data) { if (error) { _log("Error returned from Tern 'refs' request: " + error); var response = { type: MessageIds.TERN_REFS, error: error.message }; self.postMessage(response); return; } var response = { type: MessageIds.TERN_REFS, file: fileInfo.name, offset: offset, references: data }; // Post a message back to the main thread with the results self.postMessage(response); }); } catch (e) { _reportError(e, fileInfo.name); } }
javascript
{ "resource": "" }
q16804
getScopeData
train
function getScopeData(fileInfo, offset) { // Create a new tern Server // Existing tern server resolves all the required modules which might take time // We only need to analyze single file for getting the scope ternOptions.plugins = {}; var ternServer = new Tern.Server(ternOptions); ternServer.addFile(fileInfo.name, fileInfo.text); var error; var request = buildRequest(fileInfo, "completions", offset); // for primepump try { // primepump ternServer.request(request, function (ternError, data) { if (ternError) { _log("Error for Tern request: \n" + JSON.stringify(request) + "\n" + ternError); error = ternError.toString(); } else { var file = ternServer.findFile(fileInfo.name); var scope = Infer.scopeAt(file.ast, Tern.resolvePos(file, offset), file.scope); if (scope) { // Remove unwanted properties to remove cycles in the object scope = JSON.parse(JSON.stringify(scope, function(key, value) { if (["proto", "propertyOf", "onNewProp", "sourceFile", "maybeProps"].includes(key)) { return undefined; } else if (key === "fnType") { return value.name || "FunctionExpression"; } else if (key === "props") { for (var key in value) { value[key] = value[key].propertyName; } return value; } else if (key === "originNode") { return value && { start: value.start, end: value.end, type: value.type, body: { start: value.body.start, end: value.body.end } }; } return value; })); } self.postMessage({ type: MessageIds.TERN_SCOPEDATA_MSG, file: _getNormalizedFilename(fileInfo.name), offset: offset, scope: scope }); } }); } catch (e) { _reportError(e, fileInfo.name); } finally { ternServer.reset(); Infer.resetGuessing(); } }
javascript
{ "resource": "" }
q16805
getTernProperties
train
function getTernProperties(fileInfo, offset, type) { var request = buildRequest(fileInfo, "properties", offset), i; //_log("tern properties: request " + request.type + dir + " " + file); try { ternServer.request(request, function (error, data) { var properties = []; if (error) { _log("Error returned from Tern 'properties' request: " + error); } else { //_log("tern properties: completions = " + data.completions.length); properties = data.completions.map(function (completion) { return {value: completion, type: completion.type, guess: true}; }); } // Post a message back to the main thread with the completions self.postMessage({type: type, file: _getNormalizedFilename(fileInfo.name), offset: offset, properties: properties }); }); } catch (e) { _reportError(e, fileInfo.name); } }
javascript
{ "resource": "" }
q16806
getTernHints
train
function getTernHints(fileInfo, offset, isProperty) { var request = buildRequest(fileInfo, "completions", offset), i; //_log("request " + dir + " " + file + " " + offset /*+ " " + text */); try { ternServer.request(request, function (error, data) { var completions = []; if (error) { _log("Error returned from Tern 'completions' request: " + error); } else { //_log("found " + data.completions + " for " + file + "@" + offset); completions = data.completions.map(function (completion) { return {value: completion.name, type: completion.type, depth: completion.depth, guess: completion.guess, origin: completion.origin, doc: completion.doc, url: completion.url}; }); } if (completions.length > 0 || !isProperty) { // Post a message back to the main thread with the completions self.postMessage({type: MessageIds.TERN_COMPLETIONS_MSG, file: _getNormalizedFilename(fileInfo.name), offset: offset, completions: completions }); } else { // if there are no completions, then get all the properties getTernProperties(fileInfo, offset, MessageIds.TERN_COMPLETIONS_MSG); } }); } catch (e) { _reportError(e, fileInfo.name); } }
javascript
{ "resource": "" }
q16807
inferArrTypeToString
train
function inferArrTypeToString(inferArrType) { var result = "Array.<"; result += inferArrType.props["<i>"].types.map(inferTypeToString).join(", "); // workaround case where types is zero length if (inferArrType.props["<i>"].types.length === 0) { result += "Object"; } result += ">"; return result; }
javascript
{ "resource": "" }
q16808
handleFunctionType
train
function handleFunctionType(fileInfo, offset) { var request = buildRequest(fileInfo, "type", offset), error; request.query.preferFunction = true; var fnType = ""; try { ternServer.request(request, function (ternError, data) { if (ternError) { _log("Error for Tern request: \n" + JSON.stringify(request) + "\n" + ternError); error = ternError.toString(); } else { var file = ternServer.findFile(fileInfo.name); // convert query from partial to full offsets var newOffset = offset; if (fileInfo.type === MessageIds.TERN_FILE_INFO_TYPE_PART) { newOffset = {line: offset.line + fileInfo.offsetLines, ch: offset.ch}; } request = buildRequest(createEmptyUpdate(fileInfo.name), "type", newOffset); var expr = Tern.findQueryExpr(file, request.query); Infer.resetGuessing(); var type = Infer.expressionType(expr); type = type.getFunctionType() || type.getType(); if (type) { fnType = getParameters(type); } else { ternError = "No parameter type found"; _log(ternError); } } }); } catch (e) { _reportError(e, fileInfo.name); } // Post a message back to the main thread with the completions self.postMessage({type: MessageIds.TERN_CALLED_FUNC_TYPE_MSG, file: _getNormalizedFilename(fileInfo.name), offset: offset, fnType: fnType, error: error }); }
javascript
{ "resource": "" }
q16809
handleUpdateFile
train
function handleUpdateFile(path, text) { ternServer.addFile(path, text); self.postMessage({type: MessageIds.TERN_UPDATE_FILE_MSG, path: path }); // reset to get the best hints with the updated file. ternServer.reset(); Infer.resetGuessing(); }
javascript
{ "resource": "" }
q16810
handlePrimePump
train
function handlePrimePump(path) { var fileName = _getDenormalizedFilename(path); var fileInfo = createEmptyUpdate(fileName), request = buildRequest(fileInfo, "completions", {line: 0, ch: 0}); try { ternServer.request(request, function (error, data) { // Post a message back to the main thread self.postMessage({type: MessageIds.TERN_PRIME_PUMP_MSG, path: _getNormalizedFilename(path) }); }); } catch (e) { _reportError(e, path); } }
javascript
{ "resource": "" }
q16811
_updateScrollerShadow
train
function _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed) { var offsetTop = 0, scrollElement = $scrollElement.get(0), scrollTop = scrollElement.scrollTop, topShadowOffset = Math.min(scrollTop - SCROLL_SHADOW_HEIGHT, 0), displayElementWidth = $displayElement.width(); if ($shadowTop) { $shadowTop.css("background-position", "0px " + topShadowOffset + "px"); if (isPositionFixed) { offsetTop = $displayElement.offset().top; $shadowTop.css("top", offsetTop); } if (isPositionFixed) { $shadowTop.css("width", displayElementWidth); } } if ($shadowBottom) { var clientHeight = scrollElement.clientHeight, outerHeight = $displayElement.outerHeight(), scrollHeight = scrollElement.scrollHeight, bottomShadowOffset = SCROLL_SHADOW_HEIGHT; // outside of shadow div viewport if (scrollHeight > clientHeight) { bottomShadowOffset -= Math.min(SCROLL_SHADOW_HEIGHT, (scrollHeight - (scrollTop + clientHeight))); } $shadowBottom.css("background-position", "0px " + bottomShadowOffset + "px"); $shadowBottom.css("top", offsetTop + outerHeight - SCROLL_SHADOW_HEIGHT); $shadowBottom.css("width", displayElementWidth); } }
javascript
{ "resource": "" }
q16812
addScrollerShadow
train
function addScrollerShadow(displayElement, scrollElement, showBottom) { // use fixed positioning when the display and scroll elements are the same var isPositionFixed = false; if (!scrollElement) { scrollElement = displayElement; isPositionFixed = true; } // update shadows when the scrolling element is scrolled var $displayElement = $(displayElement), $scrollElement = $(scrollElement); var $shadowTop = getOrCreateShadow($displayElement, "top", isPositionFixed); var $shadowBottom = (showBottom) ? getOrCreateShadow($displayElement, "bottom", isPositionFixed) : null; var doUpdate = function () { _updateScrollerShadow($displayElement, $scrollElement, $shadowTop, $shadowBottom, isPositionFixed); }; // remove any previously installed listeners on this node $scrollElement.off("scroll.scroller-shadow"); $displayElement.off("contentChanged.scroller-shadow"); // add new ones $scrollElement.on("scroll.scroller-shadow", doUpdate); $displayElement.on("contentChanged.scroller-shadow", doUpdate); // update immediately doUpdate(); }
javascript
{ "resource": "" }
q16813
removeScrollerShadow
train
function removeScrollerShadow(displayElement, scrollElement) { if (!scrollElement) { scrollElement = displayElement; } var $displayElement = $(displayElement), $scrollElement = $(scrollElement); // remove scrollerShadow elements from DOM $displayElement.find(".scroller-shadow.top").remove(); $displayElement.find(".scroller-shadow.bottom").remove(); // remove event handlers $scrollElement.off("scroll.scroller-shadow"); $displayElement.off("contentChanged.scroller-shadow"); }
javascript
{ "resource": "" }
q16814
getElementClipSize
train
function getElementClipSize($view, elementRect) { var delta, clip = { top: 0, right: 0, bottom: 0, left: 0 }, viewOffset = $view.offset() || { top: 0, left: 0}; // Check if element extends below viewport delta = (elementRect.top + elementRect.height) - (viewOffset.top + $view.height()); if (delta > 0) { clip.bottom = delta; } // Check if element extends above viewport delta = viewOffset.top - elementRect.top; if (delta > 0) { clip.top = delta; } // Check if element extends to the left of viewport delta = viewOffset.left - elementRect.left; if (delta > 0) { clip.left = delta; } // Check if element extends to the right of viewport delta = (elementRect.left + elementRect.width) - (viewOffset.left + $view.width()); if (delta > 0) { clip.right = delta; } return clip; }
javascript
{ "resource": "" }
q16815
scrollElementIntoView
train
function scrollElementIntoView($view, $element, scrollHorizontal) { var elementOffset = $element.offset(); // scroll minimum amount var elementRect = { top: elementOffset.top, left: elementOffset.left, height: $element.height(), width: $element.width() }, clip = getElementClipSize($view, elementRect); if (clip.bottom > 0) { // below viewport $view.scrollTop($view.scrollTop() + clip.bottom); } else if (clip.top > 0) { // above viewport $view.scrollTop($view.scrollTop() - clip.top); } if (scrollHorizontal) { if (clip.left > 0) { $view.scrollLeft($view.scrollLeft() - clip.left); } else if (clip.right > 0) { $view.scrollLeft($view.scrollLeft() + clip.right); } } }
javascript
{ "resource": "" }
q16816
getFileEntryDisplay
train
function getFileEntryDisplay(entry) { var name = entry.name, ext = LanguageManager.getCompoundFileExtension(name), i = name.lastIndexOf("." + ext); if (i > 0) { // Escape all HTML-sensitive characters in filename. name = _.escape(name.substring(0, i)) + "<span class='extension'>" + _.escape(name.substring(i)) + "</span>"; } else { name = _.escape(name); } return name; }
javascript
{ "resource": "" }
q16817
getDirNamesForDuplicateFiles
train
function getDirNamesForDuplicateFiles(files) { // Must have at least two files in list for this to make sense if (files.length <= 1) { return []; } // First collect paths from the list of files and fill map with them var map = {}, filePaths = [], displayPaths = []; files.forEach(function (file, index) { var fp = file.fullPath.split("/"); fp.pop(); // Remove the filename itself displayPaths[index] = fp.pop(); filePaths[index] = fp; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } }); // This function is used to loop through map and resolve duplicate names var processMap = function (map) { var didSomething = false; _.forEach(map, function (arr, key) { // length > 1 means we have duplicates that need to be resolved if (arr.length > 1) { arr.forEach(function (index) { if (filePaths[index].length !== 0) { displayPaths[index] = filePaths[index].pop() + "/" + displayPaths[index]; didSomething = true; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } } }); } delete map[key]; }); return didSomething; }; var repeat; do { repeat = processMap(map); } while (repeat); return displayPaths; }
javascript
{ "resource": "" }
q16818
train
function (map) { var didSomething = false; _.forEach(map, function (arr, key) { // length > 1 means we have duplicates that need to be resolved if (arr.length > 1) { arr.forEach(function (index) { if (filePaths[index].length !== 0) { displayPaths[index] = filePaths[index].pop() + "/" + displayPaths[index]; didSomething = true; if (!map[displayPaths[index]]) { map[displayPaths[index]] = [index]; } else { map[displayPaths[index]].push(index); } } }); } delete map[key]; }); return didSomething; }
javascript
{ "resource": "" }
q16819
filterForKeyword
train
function filterForKeyword(extensionList, word) { var filteredList = []; extensionList.forEach(function (id) { var entry = self._getEntry(id); if (entry && self._entryMatchesQuery(entry, word)) { filteredList.push(id); } }); return filteredList; }
javascript
{ "resource": "" }
q16820
loadExtensionModule
train
function loadExtensionModule(name, config, entryPoint) { var extensionConfig = { context: name, baseUrl: config.baseUrl, paths: globalPaths, locale: brackets.getLocale() }; // Read optional requirejs-config.json var promise = _mergeConfig(extensionConfig).then(function (mergedConfig) { // Create new RequireJS context and load extension entry point var extensionRequire = brackets.libRequire.config(mergedConfig), extensionRequireDeferred = new $.Deferred(); contexts[name] = extensionRequire; extensionRequire([entryPoint], extensionRequireDeferred.resolve, extensionRequireDeferred.reject); return extensionRequireDeferred.promise(); }).then(function (module) { // Extension loaded normally var initPromise; _extensions[name] = module; // Optional sync/async initExtension if (module && module.initExtension && (typeof module.initExtension === "function")) { // optional async extension init try { initPromise = Async.withTimeout(module.initExtension(), _getInitExtensionTimeout()); } catch (err) { // Synchronous error while initializing extension console.error("[Extension] Error -- error thrown during initExtension for " + name + ": " + err); return new $.Deferred().reject(err).promise(); } // initExtension may be synchronous and may not return a promise if (initPromise) { // WARNING: These calls to initPromise.fail() and initPromise.then(), // could also result in a runtime error if initPromise is not a valid // promise. Currently, the promise is wrapped via Async.withTimeout(), // so the call is safe as-is. initPromise.fail(function (err) { if (err === Async.ERROR_TIMEOUT) { console.error("[Extension] Error -- timeout during initExtension for " + name); } else { console.error("[Extension] Error -- failed initExtension for " + name + (err ? ": " + err : "")); } }); return initPromise; } } }, function errback(err) { // Extension failed to load during the initial require() call var additionalInfo = String(err); if (err.requireType === "scripterror" && err.originalError) { // This type has a misleading error message - replace it with something clearer (URL of require() call that got a 404 result) additionalInfo = "Module does not exist: " + err.originalError.target.src; } console.error("[Extension] failed to load " + config.baseUrl + " - " + additionalInfo); if (err.requireType === "define") { // This type has a useful stack (exception thrown by ext code or info on bad getModule() call) console.log(err.stack); } }); return promise; }
javascript
{ "resource": "" }
q16821
loadExtension
train
function loadExtension(name, config, entryPoint) { var promise = new $.Deferred(); // Try to load the package.json to figure out if we are loading a theme. ExtensionUtils.loadMetadata(config.baseUrl).always(promise.resolve); return promise .then(function (metadata) { // No special handling for themes... Let the promise propagate into the ExtensionManager if (metadata && metadata.theme) { return; } if (!metadata.disabled) { return loadExtensionModule(name, config, entryPoint); } else { return new $.Deferred().reject("disabled").promise(); } }) .then(function () { exports.trigger("load", config.baseUrl); }, function (err) { if (err === "disabled") { exports.trigger("disabled", config.baseUrl); } else { exports.trigger("loadFailed", config.baseUrl); } }); }
javascript
{ "resource": "" }
q16822
init
train
function init(paths) { var params = new UrlParams(); if (_init) { // Only init once. Return a resolved promise. return new $.Deferred().resolve().promise(); } if (!paths) { params.parse(); if (params.get("reloadWithoutUserExts") === "true") { paths = ["default"]; } else { paths = [ getDefaultExtensionPath(), "dev", getUserExtensionPath() ]; } } // Load extensions before restoring the project // Get a Directory for the user extension directory and create it if it doesn't exist. // Note that this is an async call and there are no success or failure functions passed // in. If the directory *doesn't* exist, it will be created. Extension loading may happen // before the directory is finished being created, but that is okay, since the extension // loading will work correctly without this directory. // If the directory *does* exist, nothing else needs to be done. It will be scanned normally // during extension loading. var extensionPath = getUserExtensionPath(); FileSystem.getDirectoryForPath(extensionPath).create(); // Create the extensions/disabled directory, too. var disabledExtensionPath = extensionPath.replace(/\/user$/, "/disabled"); FileSystem.getDirectoryForPath(disabledExtensionPath).create(); var promise = Async.doSequentially(paths, function (item) { var extensionPath = item; // If the item has "/" in it, assume it is a full path. Otherwise, load // from our source path + "/extensions/". if (item.indexOf("/") === -1) { extensionPath = FileUtils.getNativeBracketsDirectoryPath() + "/extensions/" + item; } return loadAllExtensionsInNativeDirectory(extensionPath); }, false); promise.always(function () { _init = true; }); return promise; }
javascript
{ "resource": "" }
q16823
_applyAllCallbacks
train
function _applyAllCallbacks(callbacks, args) { if (callbacks.length > 0) { var callback = callbacks.pop(); try { callback.apply(undefined, args); } finally { _applyAllCallbacks(callbacks, args); } } }
javascript
{ "resource": "" }
q16824
doCreate
train
function doCreate(path, isFolder) { var d = new $.Deferred(); var filename = FileUtils.getBaseName(path); // Check if filename if (!isValidFilename(filename)){ return d.reject(ERROR_INVALID_FILENAME).promise(); } // Check if fullpath with filename is valid // This check is used to circumvent directory jumps (Like ../..) if (!isValidPath(path)) { return d.reject(ERROR_INVALID_FILENAME).promise(); } FileSystem.resolve(path, function (err) { if (!err) { // Item already exists, fail with error d.reject(FileSystemError.ALREADY_EXISTS); } else { if (isFolder) { var directory = FileSystem.getDirectoryForPath(path); directory.create(function (err) { if (err) { d.reject(err); } else { d.resolve(directory); } }); } else { // Create an empty file var file = FileSystem.getFileForPath(path); FileUtils.writeText(file, "").then(function () { d.resolve(file); }, d.reject); } } }); return d.promise(); }
javascript
{ "resource": "" }
q16825
_isWelcomeProjectPath
train
function _isWelcomeProjectPath(path, welcomeProjectPath, welcomeProjects) { if (path === welcomeProjectPath) { return true; } // No match on the current path, and it's not a match if there are no previously known projects if (!welcomeProjects) { return false; } var pathNoSlash = FileUtils.stripTrailingSlash(path); // "welcomeProjects" pref has standardized on no trailing "/" return welcomeProjects.indexOf(pathNoSlash) !== -1; }
javascript
{ "resource": "" }
q16826
_getVersionInfoUrl
train
function _getVersionInfoUrl(localeParam) { var locale = localeParam || brackets.getLocale(); if (locale.length > 2) { locale = locale.substring(0, 2); } return brackets.config.notification_info_url.replace("<locale>", locale); }
javascript
{ "resource": "" }
q16827
_getNotificationInformation
train
function _getNotificationInformation(_notificationInfoUrl) { // Last time the versionInfoURL was fetched var lastInfoURLFetchTime = PreferencesManager.getViewState("lastNotificationURLFetchTime"); var result = new $.Deferred(); var fetchData = false; var data; // If we don't have data saved in prefs, fetch data = PreferencesManager.getViewState("notificationInfo"); if (!data) { fetchData = true; } // If more than 24 hours have passed since our last fetch, fetch again if (Date.now() > lastInfoURLFetchTime + ONE_DAY) { fetchData = true; } if (fetchData) { var lookupPromise = new $.Deferred(), localNotificationInfoUrl; // If the current locale isn't "en" or "en-US", check whether we actually have a // locale-specific notification target, and fall back to "en" if not. var locale = brackets.getLocale().toLowerCase(); if (locale !== "en" && locale !== "en-us") { localNotificationInfoUrl = _notificationInfoUrl || _getVersionInfoUrl(); // Check if we can reach a locale specific notifications source $.ajax({ url: localNotificationInfoUrl, cache: false, type: "HEAD" }).fail(function (jqXHR, status, error) { // Fallback to "en" locale localNotificationInfoUrl = _getVersionInfoUrl("en"); }).always(function (jqXHR, status, error) { lookupPromise.resolve(); }); } else { localNotificationInfoUrl = _notificationInfoUrl || _getVersionInfoUrl("en"); lookupPromise.resolve(); } lookupPromise.done(function () { $.ajax({ url: localNotificationInfoUrl, dataType: "json", cache: false }).done(function (notificationInfo, textStatus, jqXHR) { lastInfoURLFetchTime = (new Date()).getTime(); PreferencesManager.setViewState("lastNotificationURLFetchTime", lastInfoURLFetchTime); PreferencesManager.setViewState("notificationInfo", notificationInfo); result.resolve(notificationInfo); }).fail(function (jqXHR, status, error) { // When loading data for unit tests, the error handler is // called but the responseText is valid. Try to use it here, // but *don't* save the results in prefs. if (!jqXHR.responseText) { // Text is NULL or empty string, reject(). result.reject(); return; } try { data = JSON.parse(jqXHR.responseText); result.resolve(data); } catch (e) { result.reject(); } }); }); } else { result.resolve(data); } return result.promise(); }
javascript
{ "resource": "" }
q16828
checkForNotification
train
function checkForNotification(versionInfoUrl) { var result = new $.Deferred(); _getNotificationInformation(versionInfoUrl) .done(function (notificationInfo) { // Get all available notifications var notifications = notificationInfo.notifications; if (notifications && notifications.length > 0) { // Iterate through notifications and act only on the most recent // applicable notification notifications.every(function(notificationObj) { // Only show the notification overlay if the user hasn't been // alerted of this notification if (_checkNotificationValidity(notificationObj)) { if (notificationObj.silent) { // silent notifications, to gather user validity based on filters HealthLogger.sendAnalyticsData("notification", notificationObj.sequence, "handled"); } else { showNotification(notificationObj); } // Break, we have acted on one notification already return false; } // Continue, we haven't yet got a notification to act on return true; }); } result.resolve(); }) .fail(function () { // Error fetching the update data. If this is a forced check, alert the user result.reject(); }); return result.promise(); }
javascript
{ "resource": "" }
q16829
splitNs
train
function splitNs(eventStr) { var dot = eventStr.indexOf("."); if (dot === -1) { return { eventName: eventStr }; } else { return { eventName: eventStr.substring(0, dot), ns: eventStr.substring(dot) }; } }
javascript
{ "resource": "" }
q16830
_hidePanelsIfRequired
train
function _hidePanelsIfRequired() { var panelIDs = WorkspaceManager.getAllPanelIDs(); _previouslyOpenPanelIDs = []; panelIDs.forEach(function (panelID) { var panel = WorkspaceManager.getPanelForID(panelID); if (panel && panel.isVisible()) { panel.hide(); _previouslyOpenPanelIDs.push(panelID); } }); }
javascript
{ "resource": "" }
q16831
initializeCommands
train
function initializeCommands() { CommandManager.register(Strings.CMD_TOGGLE_PURE_CODE, CMD_TOGGLE_PURE_CODE, _togglePureCode); CommandManager.register(Strings.CMD_TOGGLE_PANELS, CMD_TOGGLE_PANELS, _togglePanels); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(CMD_TOGGLE_PANELS, "", Menus.AFTER, Commands.VIEW_HIDE_SIDEBAR); Menus.getMenu(Menus.AppMenuBar.VIEW_MENU).addMenuItem(CMD_TOGGLE_PURE_CODE, "", Menus.AFTER, CMD_TOGGLE_PANELS); KeyBindingManager.addBinding(CMD_TOGGLE_PURE_CODE, [ {key: togglePureCodeKey}, {key: togglePureCodeKeyMac, platform: "mac"} ]); //default toggle panel shortcut was ctrl+shift+` as it is present in one vertical line in the keyboard. However, we later learnt //from IQE team than non-English keyboards does not have the ` char. So added one more shortcut ctrl+shift+1 which will be preferred KeyBindingManager.addBinding(CMD_TOGGLE_PANELS, [ {key: togglePanelsKey}, {key: togglePanelsKeyMac, platform: "mac"} ]); KeyBindingManager.addBinding(CMD_TOGGLE_PANELS, [ {key: togglePanelsKey_EN}, {key: togglePanelsKeyMac_EN, platform: "mac"} ]); }
javascript
{ "resource": "" }
q16832
_findChangedCharacters
train
function _findChangedCharacters(oldValue, value) { if (oldValue === value) { return undefined; } var length = oldValue.length; var index = 0; // find the first character that changed var i; for (i = 0; i < length; i++) { if (value[i] !== oldValue[i]) { break; } } index += i; value = value.substr(i); length -= i; // find the last character that changed for (i = 0; i < length; i++) { if (value[value.length - 1 - i] !== oldValue[oldValue.length - 1 - i]) { break; } } length -= i; value = value.substr(0, value.length - i); return { from: index, to: index + length, text: value }; }
javascript
{ "resource": "" }
q16833
updateResizeLimits
train
function updateResizeLimits() { var editorAreaHeight = $editorHolder.height(); $editorHolder.siblings().each(function (i, elem) { var $elem = $(elem); if ($elem.css("display") === "none") { $elem.data("maxsize", editorAreaHeight); } else { $elem.data("maxsize", editorAreaHeight + $elem.outerHeight()); } }); }
javascript
{ "resource": "" }
q16834
handleWindowResize
train
function handleWindowResize() { // These are not initialized in Jasmine Spec Runner window until a test // is run that creates a mock document. if (!$windowContent || !$editorHolder) { return; } // FIXME (issue #4564) Workaround https://github.com/codemirror/CodeMirror/issues/1787 triggerUpdateLayout(); if (!windowResizing) { windowResizing = true; // We don't need any fancy debouncing here - we just need to react before the user can start // resizing any panels at the new window size. So just listen for first mousemove once the // window resize releases mouse capture. $(window.document).one("mousemove", function () { windowResizing = false; updateResizeLimits(); }); } }
javascript
{ "resource": "" }
q16835
createBottomPanel
train
function createBottomPanel(id, $panel, minSize) { $panel.insertBefore("#status-bar"); $panel.hide(); updateResizeLimits(); // initialize panel's max size panelIDMap[id] = new Panel($panel, minSize); panelIDMap[id].panelID = id; return panelIDMap[id]; }
javascript
{ "resource": "" }
q16836
getAllPanelIDs
train
function getAllPanelIDs() { var property, panelIDs = []; for (property in panelIDMap) { if (panelIDMap.hasOwnProperty(property)) { panelIDs.push(property); } } return panelIDs; }
javascript
{ "resource": "" }
q16837
getAggregatedHealthData
train
function getAggregatedHealthData() { var healthData = getStoredHealthData(); $.extend(healthData, PerfUtils.getHealthReport()); $.extend(healthData, FindUtils.getHealthReport()); return healthData; }
javascript
{ "resource": "" }
q16838
setHealthDataLog
train
function setHealthDataLog(key, dataObject) { var healthData = getStoredHealthData(); healthData[key] = dataObject; setHealthData(healthData); }
javascript
{ "resource": "" }
q16839
fileOpened
train
function fileOpened(filePath, addedToWorkingSet, encoding) { if (!shouldLogHealthData()) { return; } var fileExtension = FileUtils.getFileExtension(filePath), language = LanguageManager.getLanguageForPath(filePath), healthData = getStoredHealthData(), fileExtCountMap = []; healthData.fileStats = healthData.fileStats || { openedFileExt : {}, workingSetFileExt : {}, openedFileEncoding: {} }; if (language.getId() !== "unknown") { fileExtCountMap = addedToWorkingSet ? healthData.fileStats.workingSetFileExt : healthData.fileStats.openedFileExt; if (!fileExtCountMap[fileExtension]) { fileExtCountMap[fileExtension] = 0; } fileExtCountMap[fileExtension]++; setHealthData(healthData); } if (encoding) { var fileEncCountMap = healthData.fileStats.openedFileEncoding; if (!fileEncCountMap) { healthData.fileStats.openedFileEncoding = {}; fileEncCountMap = healthData.fileStats.openedFileEncoding; } if (!fileEncCountMap[encoding]) { fileEncCountMap[encoding] = 0; } fileEncCountMap[encoding]++; setHealthData(healthData); } sendAnalyticsData(commonStrings.USAGE + commonStrings.FILE_OPEN + language._name, commonStrings.USAGE, commonStrings.FILE_OPEN, language._name.toLowerCase() ); }
javascript
{ "resource": "" }
q16840
fileSaved
train
function fileSaved(docToSave) { if (!docToSave) { return; } var fileType = docToSave.language ? docToSave.language._name : ""; sendAnalyticsData(commonStrings.USAGE + commonStrings.FILE_SAVE + fileType, commonStrings.USAGE, commonStrings.FILE_SAVE, fileType.toLowerCase() ); }
javascript
{ "resource": "" }
q16841
fileClosed
train
function fileClosed(file) { if (!file) { return; } var language = LanguageManager.getLanguageForPath(file._path), size = -1; function _sendData(fileSize) { var subType = ""; if(fileSize/1024 <= 1) { if(fileSize < 0) { subType = ""; } if(fileSize <= 10) { subType = "Size_0_10KB"; } else if (fileSize <= 50) { subType = "Size_10_50KB"; } else if (fileSize <= 100) { subType = "Size_50_100KB"; } else if (fileSize <= 500) { subType = "Size_100_500KB"; } else { subType = "Size_500KB_1MB"; } } else { fileSize = fileSize/1024; if(fileSize <= 2) { subType = "Size_1_2MB"; } else if(fileSize <= 5) { subType = "Size_2_5MB"; } else { subType = "Size_Above_5MB"; } } sendAnalyticsData(commonStrings.USAGE + commonStrings.FILE_CLOSE + language._name + subType, commonStrings.USAGE, commonStrings.FILE_CLOSE, language._name.toLowerCase(), subType ); } file.stat(function(err, fileStat) { if(!err) { size = fileStat.size.valueOf()/1024; } _sendData(size); }); }
javascript
{ "resource": "" }
q16842
searchDone
train
function searchDone(searchType) { var searchDetails = getHealthDataLog("searchDetails"); if (!searchDetails) { searchDetails = {}; } if (!searchDetails[searchType]) { searchDetails[searchType] = 0; } searchDetails[searchType]++; setHealthDataLog("searchDetails", searchDetails); }
javascript
{ "resource": "" }
q16843
sendAnalyticsData
train
function sendAnalyticsData(eventName, eventCategory, eventSubCategory, eventType, eventSubType) { var isEventDataAlreadySent = analyticsEventMap.get(eventName), isHDTracking = PreferencesManager.getExtensionPrefs("healthData").get("healthDataTracking"), eventParams = {}; if (isHDTracking && !isEventDataAlreadySent && eventName && eventCategory) { eventParams = { eventName: eventName, eventCategory: eventCategory, eventSubCategory: eventSubCategory || "", eventType: eventType || "", eventSubType: eventSubType || "" }; notifyHealthManagerToSendData(eventParams); } }
javascript
{ "resource": "" }
q16844
isStaticHtmlFileExt
train
function isStaticHtmlFileExt(filePath) { if (!filePath) { return false; } return (_staticHtmlFileExts.indexOf(LanguageManager.getLanguageForPath(filePath).getId()) !== -1); }
javascript
{ "resource": "" }
q16845
isServerHtmlFileExt
train
function isServerHtmlFileExt(filePath) { if (!filePath) { return false; } return (_serverHtmlFileExts.indexOf(LanguageManager.getLanguageForPath(filePath).getId()) !== -1); }
javascript
{ "resource": "" }
q16846
updateDirtyFilesCache
train
function updateDirtyFilesCache(name, action) { if (action) { _dirtyFilesCache[name] = true; } else { if (_dirtyFilesCache[name]) { delete _dirtyFilesCache[name]; } } }
javascript
{ "resource": "" }
q16847
InstallExtensionDialog
train
function InstallExtensionDialog(installer, _isUpdate) { this._installer = installer; this._state = STATE_CLOSED; this._installResult = null; this._isUpdate = _isUpdate; // Timeout before we allow user to leave STATE_INSTALL_CANCELING without waiting for a resolution // (per-instance so we can poke it for unit testing) this._cancelTimeout = 10 * 1000; }
javascript
{ "resource": "" }
q16848
get
train
function get(command) { var commandID; if (!command) { console.error("Attempting to get a Sort method with a missing required parameter: command"); return; } if (typeof command === "string") { commandID = command; } else { commandID = command.getID(); } return _sorts[commandID]; }
javascript
{ "resource": "" }
q16849
_convertSortPref
train
function _convertSortPref(sortMethod) { if (!sortMethod) { return null; } if (_sortPrefConversionMap.hasOwnProperty(sortMethod)) { sortMethod = _sortPrefConversionMap[sortMethod]; PreferencesManager.setViewState(_WORKING_SET_SORT_PREF, sortMethod); } else { sortMethod = null; } return sortMethod; }
javascript
{ "resource": "" }
q16850
_addListeners
train
function _addListeners() { if (_automaticSort && _currentSort && _currentSort.getEvents()) { MainViewManager .on(_currentSort.getEvents(), function () { _currentSort.sort(); }) .on("_workingSetDisableAutoSort.sort", function () { setAutomatic(false); }); } }
javascript
{ "resource": "" }
q16851
_setCurrentSort
train
function _setCurrentSort(newSort) { if (_currentSort !== newSort) { if (_currentSort !== null) { _currentSort.setChecked(false); } if (_automaticSort) { newSort.setChecked(true); } CommandManager.get(Commands.CMD_WORKING_SORT_TOGGLE_AUTO).setEnabled(!!newSort.getEvents()); PreferencesManager.setViewState(_WORKING_SET_SORT_PREF, newSort.getCommandID()); _currentSort = newSort; } }
javascript
{ "resource": "" }
q16852
register
train
function register(command, compareFn, events) { var commandID = ""; if (!command || !compareFn) { console.log("Attempting to register a Sort method with a missing required parameter: command or compare function"); return; } if (typeof command === "string") { commandID = command; } else { commandID = command.getID(); } if (_sorts[commandID]) { console.log("Attempting to register an already-registered Sort method: " + command); return; } // Adds ".sort" to the end of each event to make them specific for the automatic sort. if (events) { events = events.split(" "); events.forEach(function (event, index) { events[index] = events[index].trim() + ".sort"; }); events = events.join(" "); } var sort = new Sort(commandID, compareFn, events); _sorts[commandID] = sort; return sort; }
javascript
{ "resource": "" }
q16853
train
function () { var attributeString = JSON.stringify(this.attributes); this.attributeSignature = MurmurHash3.hashString(attributeString, attributeString.length, seed); }
javascript
{ "resource": "" }
q16854
allNodesAtLocation
train
function allNodesAtLocation(location) { var nodes = []; exports.root.each(function each(n) { if (n.type === DOMNode.TYPE_ELEMENT && n.isAtLocation(location)) { nodes.push(n); } }); return nodes; }
javascript
{ "resource": "" }
q16855
nodeAtLocation
train
function nodeAtLocation(location) { return exports.root.find(function each(n) { return n.isAtLocation(location, false); }); }
javascript
{ "resource": "" }
q16856
_cleanURL
train
function _cleanURL(url) { var index = url.search(/[#\?]/); if (index >= 0) { url = url.substr(0, index); } return url; }
javascript
{ "resource": "" }
q16857
_mapDocumentToSource
train
function _mapDocumentToSource(source) { var node = exports.root; DOMHelpers.eachNode(source, function each(payload) { if (!node) { return true; } if (payload.closing) { var parent = node.findParentForNextNodeMatchingPayload(payload); if (!parent) { return console.warn("Matching Parent not at " + payload.sourceOffset + " (" + payload.nodeName + ")"); } parent.closeLocation = payload.sourceOffset; parent.closeLength = payload.sourceLength; } else { var next = node.findNextNodeMatchingPayload(payload); if (!next) { return console.warn("Skipping Source Node at " + payload.sourceOffset); } node = next; node.location = payload.sourceOffset; node.length = payload.sourceLength; if (payload.closed) { node.closed = payload.closed; } } }); }
javascript
{ "resource": "" }
q16858
_onFinishedLoadingDOM
train
function _onFinishedLoadingDOM() { var request = new XMLHttpRequest(); request.open("GET", exports.url); request.onload = function onLoad() { if ((request.status >= 200 && request.status < 300) || request.status === 304 || request.status === 0) { _mapDocumentToSource(request.response); _load.resolve(); } else { var msg = "Received status " + request.status + " from XMLHttpRequest while attempting to load source file at " + exports.url; _load.reject(msg, { message: msg }); } }; request.onerror = function onError() { var msg = "Could not load source file at " + exports.url; _load.reject(msg, { message: msg }); }; request.send(null); }
javascript
{ "resource": "" }
q16859
applyChange
train
function applyChange(from, to, text) { var delta = from - to + text.length; var node = nodeAtLocation(from); // insert a text node if (!node) { if (!(/^\s*$/).test(text)) { console.warn("Inserting nodes not supported."); node = nodeBeforeLocation(from); } } else if (node.type === 3) { // update a text node var value = node.value.substr(0, from - node.location); value += text; value += node.value.substr(to - node.location); node.value = value; if (!EditAgent.isEditing) { // only update the DOM if the change was not caused by the edit agent Inspector.DOM.setNodeValue(node.nodeId, node.value); } } else { console.warn("Changing non-text nodes not supported."); } // adjust the location of all nodes after the change if (node) { node.length += delta; exports.root.each(function each(n) { if (n.location > node.location) { n.location += delta; } if (n.closeLocation !== undefined && n.closeLocation > node.location) { n.closeLocation += delta; } }); } }
javascript
{ "resource": "" }
q16860
_validateNonEmptyString
train
function _validateNonEmptyString(value, description, deferred) { var reportError = deferred ? deferred.reject : console.error; // http://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript if (Object.prototype.toString.call(value) !== "[object String]") { reportError(description + " must be a string"); return false; } if (value === "") { reportError(description + " must not be empty"); return false; } return true; }
javascript
{ "resource": "" }
q16861
_patchCodeMirror
train
function _patchCodeMirror() { var _original_CodeMirror_defineMode = CodeMirror.defineMode; function _wrapped_CodeMirror_defineMode(name) { if (CodeMirror.modes[name]) { console.error("There already is a CodeMirror mode with the name \"" + name + "\""); return; } _original_CodeMirror_defineMode.apply(CodeMirror, arguments); } CodeMirror.defineMode = _wrapped_CodeMirror_defineMode; }
javascript
{ "resource": "" }
q16862
_setLanguageForMode
train
function _setLanguageForMode(mode, language) { if (_modeToLanguageMap[mode]) { console.warn("CodeMirror mode \"" + mode + "\" is already used by language " + _modeToLanguageMap[mode]._name + " - cannot fully register language " + language._name + " using the same mode. Some features will treat all content with this mode as language " + _modeToLanguageMap[mode]._name); return; } _modeToLanguageMap[mode] = language; }
javascript
{ "resource": "" }
q16863
_getLanguageForMode
train
function _getLanguageForMode(mode) { var language = _modeToLanguageMap[mode]; if (language) { return language; } // In case of unsupported languages console.log("Called LanguageManager._getLanguageForMode with a mode for which no language has been registered:", mode); return _fallbackLanguage; }
javascript
{ "resource": "" }
q16864
defineLanguage
train
function defineLanguage(id, definition) { var result = new $.Deferred(); if (_pendingLanguages[id]) { result.reject("Language \"" + id + "\" is waiting to be resolved."); return result.promise(); } if (_languages[id]) { result.reject("Language \"" + id + "\" is already defined"); return result.promise(); } var language = new Language(), name = definition.name, fileExtensions = definition.fileExtensions, fileNames = definition.fileNames, blockComment = definition.blockComment, lineComment = definition.lineComment, i, l; function _finishRegisteringLanguage() { if (fileExtensions) { for (i = 0, l = fileExtensions.length; i < l; i++) { language.addFileExtension(fileExtensions[i]); } } // register language file names after mode has loaded if (fileNames) { for (i = 0, l = fileNames.length; i < l; i++) { language.addFileName(fileNames[i]); } } language._setBinary(!!definition.isBinary); // store language to language map _languages[language.getId()] = language; // restore any preferences for non-default languages if(PreferencesManager) { _updateFromPrefs(_EXTENSION_MAP_PREF); _updateFromPrefs(_NAME_MAP_PREF); } } if (!language._setId(id) || !language._setName(name) || (blockComment && !language.setBlockCommentSyntax(blockComment[0], blockComment[1])) || (lineComment && !language.setLineCommentSyntax(lineComment))) { result.reject(); return result.promise(); } if (definition.isBinary) { // add file extensions and store language to language map _finishRegisteringLanguage(); result.resolve(language); // Not notifying DocumentManager via event LanguageAdded, because DocumentManager // does not care about binary files. } else { // track languages that are currently loading _pendingLanguages[id] = language; language._loadAndSetMode(definition.mode).done(function () { // globally associate mode to language _setLanguageForMode(language.getMode(), language); // add file extensions and store language to language map _finishRegisteringLanguage(); // fire an event to notify DocumentManager of the new language _triggerLanguageAdded(language); result.resolve(language); }).fail(function (error) { console.error(error); result.reject(error); }).always(function () { // delete from pending languages after success and failure delete _pendingLanguages[id]; }); } return result.promise(); }
javascript
{ "resource": "" }
q16865
addPopUp
train
function addPopUp($popUp, removeHandler, autoRemove) { autoRemove = autoRemove || false; _popUps.push($popUp[0]); $popUp.data("PopUpManager-autoRemove", autoRemove); $popUp.data("PopUpManager-removeHandler", removeHandler); }
javascript
{ "resource": "" }
q16866
handleError
train
function handleError(message, url, line) { // Ignore this error if it does not look like the rather vague cross origin error in Chrome // Chrome will print it to the console anyway if (!testCrossOriginError(message, url, line)) { if (previousErrorHandler) { return previousErrorHandler(message, url, line); } return; } // Show an error message window.alert("Oops! This application doesn't run in browsers yet.\n\nIt is built in HTML, but right now it runs as a desktop app so you can use it to edit local files. Please use the application shell in the following repo to run this application:\n\ngithub.com/adobe/brackets-shell"); // Restore the original handler for later errors window.onerror = previousErrorHandler; }
javascript
{ "resource": "" }
q16867
_loadStyles
train
function _loadStyles() { var lessText = require("text!LiveDevelopment/main.less"); less.render(lessText, function onParse(err, tree) { console.assert(!err, err); ExtensionUtils.addEmbeddedStyleSheet(tree.css); }); }
javascript
{ "resource": "" }
q16868
_setLabel
train
function _setLabel($btn, text, style, tooltip) { // Clear text/styles from previous status $("span", $btn).remove(); $btn.removeClass(_allStatusStyles); // Set text/styles for new status if (text && text.length > 0) { $("<span class=\"label\">") .addClass(style) .text(text) .appendTo($btn); } else { $btn.addClass(style); } if (tooltip) { $btn.attr("title", tooltip); } }
javascript
{ "resource": "" }
q16869
_handleGoLiveCommand
train
function _handleGoLiveCommand() { if (LiveDevImpl.status >= LiveDevImpl.STATUS_ACTIVE) { LiveDevImpl.close(); } else if (LiveDevImpl.status <= LiveDevImpl.STATUS_INACTIVE) { if (!params.get("skipLiveDevelopmentInfo") && !PreferencesManager.getViewState("livedev.afterFirstLaunch")) { PreferencesManager.setViewState("livedev.afterFirstLaunch", "true"); Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_INFO, Strings.LIVE_DEVELOPMENT_INFO_TITLE, Strings.LIVE_DEVELOPMENT_INFO_MESSAGE ).done(function (id) { LiveDevImpl.open(); }); } else { LiveDevImpl.open(); } } }
javascript
{ "resource": "" }
q16870
_showStatusChangeReason
train
function _showStatusChangeReason(reason) { // Destroy the previous twipsy (options are not updated otherwise) _$btnGoLive.twipsy("hide").removeData("twipsy"); // If there was no reason or the action was an explicit request by the user, don't show a twipsy if (!reason || reason === "explicit_close") { return; } // Translate the reason var translatedReason = Strings["LIVE_DEV_" + reason.toUpperCase()]; if (!translatedReason) { translatedReason = StringUtils.format(Strings.LIVE_DEV_CLOSED_UNKNOWN_REASON, reason); } // Configure the twipsy var options = { placement: "left", trigger: "manual", autoHideDelay: 5000, title: function () { return translatedReason; } }; // Show the twipsy with the explanation _$btnGoLive.twipsy(options).twipsy("show"); }
javascript
{ "resource": "" }
q16871
_setupGoLiveButton
train
function _setupGoLiveButton() { if (!_$btnGoLive) { _$btnGoLive = $("#toolbar-go-live"); _$btnGoLive.click(function onGoLive() { _handleGoLiveCommand(); }); } LiveDevImpl.on("statusChange", function statusChange(event, status, reason) { // status starts at -1 (error), so add one when looking up name and style // See the comments at the top of LiveDevelopment.js for details on the // various status codes. _setLabel(_$btnGoLive, null, _status[status + 1].style, _status[status + 1].tooltip); _showStatusChangeReason(reason); if (config.autoconnect) { window.sessionStorage.setItem("live.enabled", status === 3); } }); // Initialize tooltip for 'not connected' state _setLabel(_$btnGoLive, null, _status[1].style, _status[1].tooltip); }
javascript
{ "resource": "" }
q16872
_setupGoLiveMenu
train
function _setupGoLiveMenu() { LiveDevImpl.on("statusChange", function statusChange(event, status) { // Update the checkmark next to 'Live Preview' menu item // Add checkmark when status is STATUS_ACTIVE; otherwise remove it CommandManager.get(Commands.FILE_LIVE_FILE_PREVIEW).setChecked(status === LiveDevImpl.STATUS_ACTIVE); CommandManager.get(Commands.FILE_LIVE_HIGHLIGHT).setEnabled(status === LiveDevImpl.STATUS_ACTIVE); }); }
javascript
{ "resource": "" }
q16873
_setImplementation
train
function _setImplementation(multibrowser) { if (multibrowser) { // set implemenation LiveDevImpl = MultiBrowserLiveDev; // update styles for UI status _status = [ { tooltip: Strings.LIVE_DEV_STATUS_TIP_NOT_CONNECTED, style: "warning" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_NOT_CONNECTED, style: "" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_PROGRESS1, style: "info" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_CONNECTED, style: "success" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_OUT_OF_SYNC, style: "out-of-sync" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_SYNC_ERROR, style: "sync-error" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_PROGRESS1, style: "info" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_PROGRESS1, style: "info" } ]; } else { LiveDevImpl = LiveDevelopment; _status = [ { tooltip: Strings.LIVE_DEV_STATUS_TIP_NOT_CONNECTED, style: "warning" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_NOT_CONNECTED, style: "" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_PROGRESS1, style: "info" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_PROGRESS2, style: "info" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_CONNECTED, style: "success" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_OUT_OF_SYNC, style: "out-of-sync" }, { tooltip: Strings.LIVE_DEV_STATUS_TIP_SYNC_ERROR, style: "sync-error" } ]; } // setup status changes listeners for new implementation _setupGoLiveButton(); _setupGoLiveMenu(); // toggle the menu _toggleLivePreviewMultiBrowser(multibrowser); }
javascript
{ "resource": "" }
q16874
_setupDebugHelpers
train
function _setupDebugHelpers() { window.ld = LiveDevelopment; window.i = Inspector; window.report = function report(params) { window.params = params; console.info(params); }; }
javascript
{ "resource": "" }
q16875
checkIfAnotherSessionInProgress
train
function checkIfAnotherSessionInProgress() { var result = $.Deferred(); if(updateJsonHandler) { var state = updateJsonHandler.state; updateJsonHandler.refresh() .done(function() { var val = updateJsonHandler.get(updateProgressKey); if(val !== null) { result.resolve(val); } else { result.reject(); } }) .fail(function() { updateJsonHandler.state = state; result.reject(); }); } return result.promise(); }
javascript
{ "resource": "" }
q16876
receiveMessageFromNode
train
function receiveMessageFromNode(event, msgObj) { if (functionMap[msgObj.fn]) { if(domainID === msgObj.requester) { functionMap[msgObj.fn].apply(null, msgObj.args); } } }
javascript
{ "resource": "" }
q16877
postMessageToNode
train
function postMessageToNode(messageId) { var msg = { fn: messageId, args: getFunctionArgs(arguments), requester: domainID }; updateDomain.exec('data', msg); }
javascript
{ "resource": "" }
q16878
checkInstallationStatus
train
function checkInstallationStatus() { var searchParams = { "updateDir": updateDir, "installErrorStr": ["ERROR:"], "bracketsErrorStr": ["ERROR:"], "encoding": "utf8" }, // Below are the possible Windows Installer error strings, which will be searched for in the installer logs to track failures. winInstallErrorStrArr = [ "Installation success or error status", "Reconfiguration success or error status" ]; if (brackets.platform === "win") { searchParams.installErrorStr = winInstallErrorStrArr; searchParams.encoding = "utf16le"; } postMessageToNode(MessageIds.CHECK_INSTALLER_STATUS, searchParams); }
javascript
{ "resource": "" }
q16879
checkUpdateStatus
train
function checkUpdateStatus() { var filesToCache = ['.logs'], downloadCompleted = updateJsonHandler.get("downloadCompleted"), updateInitiatedInPrevSession = updateJsonHandler.get("updateInitiatedInPrevSession"); if (downloadCompleted && updateInitiatedInPrevSession) { var isNewVersion = checkIfVersionUpdated(); updateJsonHandler.reset(); if (isNewVersion) { // We get here if the update was successful UpdateInfoBar.showUpdateBar({ type: "success", title: Strings.UPDATE_SUCCESSFUL, description: "" }); HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_INSTALLATION_SUCCESS, "autoUpdate", "install", "complete", "" ); } else { // We get here if the update started but failed checkInstallationStatus(); UpdateInfoBar.showUpdateBar({ type: "error", title: Strings.UPDATE_FAILED, description: Strings.GO_TO_SITE }); } } else if (downloadCompleted && !updateInitiatedInPrevSession) { // We get here if the download was complete and user selected UpdateLater if (brackets.platform === "mac") { filesToCache = ['.dmg', '.json']; } else if (brackets.platform === "win") { filesToCache = ['.msi', '.json']; } } postMessageToNode(MessageIds.PERFORM_CLEANUP, filesToCache); }
javascript
{ "resource": "" }
q16880
handleInstallationStatus
train
function handleInstallationStatus(statusObj) { var errorCode = "", errorline = statusObj.installError; if (errorline) { errorCode = errorline.substr(errorline.lastIndexOf(':') + 2, errorline.length); } HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_INSTALLATION_FAILED, "autoUpdate", "install", "fail", errorCode ); }
javascript
{ "resource": "" }
q16881
initState
train
function initState() { var result = $.Deferred(); updateJsonHandler.parse() .done(function() { result.resolve(); }) .fail(function (code) { var logMsg; switch (code) { case StateHandlerMessages.FILE_NOT_FOUND: logMsg = "AutoUpdate : updateHelper.json cannot be parsed, does not exist"; break; case StateHandlerMessages.FILE_NOT_READ: logMsg = "AutoUpdate : updateHelper.json could not be read"; break; case StateHandlerMessages.FILE_PARSE_EXCEPTION: logMsg = "AutoUpdate : updateHelper.json could not be parsed, exception encountered"; break; case StateHandlerMessages.FILE_READ_FAIL: logMsg = "AutoUpdate : updateHelper.json could not be parsed"; break; } console.log(logMsg); result.reject(); }); return result.promise(); }
javascript
{ "resource": "" }
q16882
setupAutoUpdate
train
function setupAutoUpdate() { updateJsonHandler = new StateHandler(updateJsonPath); updateDomain.on('data', receiveMessageFromNode); updateDomain.exec('initNode', { messageIds: MessageIds, updateDir: updateDir, requester: domainID }); }
javascript
{ "resource": "" }
q16883
initializeState
train
function initializeState() { var result = $.Deferred(); FileSystem.resolve(updateDir, function (err) { if (!err) { result.resolve(); } else { var directory = FileSystem.getDirectoryForPath(updateDir); directory.create(function (error) { if (error) { console.error('AutoUpdate : Error in creating update directory in Appdata'); result.reject(); } else { result.resolve(); } }); } }); return result.promise(); }
javascript
{ "resource": "" }
q16884
initiateAutoUpdate
train
function initiateAutoUpdate(updateParams) { _updateParams = updateParams; downloadAttemptsRemaining = MAX_DOWNLOAD_ATTEMPTS; initializeState() .done(function () { var setUpdateInProgress = function() { var initNodeFn = function () { isAutoUpdateInitiated = true; postMessageToNode(MessageIds.INITIALIZE_STATE, _updateParams); }; if (updateJsonHandler.get('latestBuildNumber') !== _updateParams.latestBuildNumber) { setUpdateStateInJSON('latestBuildNumber', _updateParams.latestBuildNumber) .done(initNodeFn); } else { initNodeFn(); } }; checkIfAnotherSessionInProgress() .done(function(inProgress) { if(inProgress) { UpdateInfoBar.showUpdateBar({ type: "error", title: Strings.AUTOUPDATE_ERROR, description: Strings.AUTOUPDATE_IN_PROGRESS }); } else { setUpdateStateInJSON("autoUpdateInProgress", true) .done(setUpdateInProgress); } }) .fail(function() { setUpdateStateInJSON("autoUpdateInProgress", true) .done(setUpdateInProgress); }); }) .fail(function () { UpdateInfoBar.showUpdateBar({ type: "error", title: Strings.INITIALISATION_FAILED, description: "" }); }); }
javascript
{ "resource": "" }
q16885
resetStateInFailure
train
function resetStateInFailure(message) { updateJsonHandler.reset(); UpdateInfoBar.showUpdateBar({ type: "error", title: Strings.UPDATE_FAILED, description: "" }); enableCheckForUpdateEntry(true); console.error(message); }
javascript
{ "resource": "" }
q16886
setUpdateStateInJSON
train
function setUpdateStateInJSON(key, value) { var result = $.Deferred(); updateJsonHandler.set(key, value) .done(function () { result.resolve(); }) .fail(function () { resetStateInFailure("AutoUpdate : Could not modify updatehelper.json"); result.reject(); }); return result.promise(); }
javascript
{ "resource": "" }
q16887
handleSafeToDownload
train
function handleSafeToDownload() { var downloadFn = function () { if (isFirstIterationDownload()) { // For the first iteration of download, show download //status info in Status bar, and pass download to node UpdateStatus.showUpdateStatus("initial-download"); postMessageToNode(MessageIds.DOWNLOAD_INSTALLER, true); } else { /* For the retry iterations of download, modify the download status info in Status bar, and pass download to node */ var attempt = (MAX_DOWNLOAD_ATTEMPTS - downloadAttemptsRemaining); if (attempt > 1) { var info = attempt.toString() + "/5"; var status = { target: "retry-download", spans: [{ id: "attempt", val: info }] }; UpdateStatus.modifyUpdateStatus(status); } else { UpdateStatus.showUpdateStatus("retry-download"); } postMessageToNode(MessageIds.DOWNLOAD_INSTALLER, false); } --downloadAttemptsRemaining; }; if(!isAutoUpdateInitiated) { isAutoUpdateInitiated = true; updateJsonHandler.refresh() .done(function() { setUpdateStateInJSON('downloadCompleted', false) .done(downloadFn); }); } else { setUpdateStateInJSON('downloadCompleted', false) .done(downloadFn); } }
javascript
{ "resource": "" }
q16888
attemptToDownload
train
function attemptToDownload() { if (checkIfOnline()) { postMessageToNode(MessageIds.PERFORM_CLEANUP, ['.json'], true); } else { enableCheckForUpdateEntry(true); UpdateStatus.cleanUpdateStatus(); HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_FAILED, "autoUpdate", "download", "fail", "No Internet connection available." ); UpdateInfoBar.showUpdateBar({ type: "warning", title: Strings.DOWNLOAD_FAILED, description: Strings.INTERNET_UNAVAILABLE }); setUpdateStateInJSON("autoUpdateInProgress", false); } }
javascript
{ "resource": "" }
q16889
showStatusInfo
train
function showStatusInfo(statusObj) { if (statusObj.target === "initial-download") { HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_START, "autoUpdate", "download", "started", "" ); UpdateStatus.modifyUpdateStatus(statusObj); } UpdateStatus.displayProgress(statusObj); }
javascript
{ "resource": "" }
q16890
showErrorMessage
train
function showErrorMessage(message) { var analyticsDescriptionMessage = ""; switch (message) { case _nodeErrorMessages.UPDATEDIR_READ_FAILED: analyticsDescriptionMessage = "Update directory could not be read."; break; case _nodeErrorMessages.UPDATEDIR_CLEAN_FAILED: analyticsDescriptionMessage = "Update directory could not be cleaned."; break; } console.log("AutoUpdate : Clean-up failed! Reason : " + analyticsDescriptionMessage + ".\n"); HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_CLEANUP_FAILED, "autoUpdate", "cleanUp", "fail", analyticsDescriptionMessage ); }
javascript
{ "resource": "" }
q16891
initiateUpdateProcess
train
function initiateUpdateProcess(formattedInstallerPath, formattedLogFilePath, installStatusFilePath) { // Get additional update parameters on Mac : installDir, appName, and updateDir function getAdditionalParams() { var retval = {}; var installDir = FileUtils.getNativeBracketsDirectoryPath(); if (installDir) { var appPath = installDir.split("/Contents/www")[0]; installDir = appPath.substr(0, appPath.lastIndexOf('/')); var appName = appPath.substr(appPath.lastIndexOf('/') + 1); retval = { installDir: installDir, appName: appName, updateDir: updateDir }; } return retval; } // Update function, to carry out app update var updateFn = function () { var infoObj = { installerPath: formattedInstallerPath, logFilePath: formattedLogFilePath, installStatusFilePath: installStatusFilePath }; if (brackets.platform === "mac") { var additionalParams = getAdditionalParams(), key; for (key in additionalParams) { if (additionalParams.hasOwnProperty(key)) { infoObj[key] = additionalParams[key]; } } } // Set update parameters for app update if (brackets.app.setUpdateParams) { brackets.app.setUpdateParams(JSON.stringify(infoObj), function (err) { if (err) { resetStateInFailure("AutoUpdate : Update parameters could not be set for the installer. Error encountered: " + err); } else { setAppQuitHandler(); CommandManager.execute(Commands.FILE_QUIT); } }); } else { resetStateInFailure("AutoUpdate : setUpdateParams could not be found in shell"); } }; setUpdateStateInJSON('updateInitiatedInPrevSession', true) .done(updateFn); }
javascript
{ "resource": "" }
q16892
train
function () { var infoObj = { installerPath: formattedInstallerPath, logFilePath: formattedLogFilePath, installStatusFilePath: installStatusFilePath }; if (brackets.platform === "mac") { var additionalParams = getAdditionalParams(), key; for (key in additionalParams) { if (additionalParams.hasOwnProperty(key)) { infoObj[key] = additionalParams[key]; } } } // Set update parameters for app update if (brackets.app.setUpdateParams) { brackets.app.setUpdateParams(JSON.stringify(infoObj), function (err) { if (err) { resetStateInFailure("AutoUpdate : Update parameters could not be set for the installer. Error encountered: " + err); } else { setAppQuitHandler(); CommandManager.execute(Commands.FILE_QUIT); } }); } else { resetStateInFailure("AutoUpdate : setUpdateParams could not be found in shell"); } }
javascript
{ "resource": "" }
q16893
handleValidationStatus
train
function handleValidationStatus(statusObj) { enableCheckForUpdateEntry(true); UpdateStatus.cleanUpdateStatus(); if (statusObj.valid) { // Installer is validated successfully var statusValidFn = function () { // Restart button click handler var restartBtnClicked = function () { HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_RESTART, "autoUpdate", "installNotification", "installNow ", "click" ); detachUpdateBarBtnHandlers(); initiateUpdateProcess(statusObj.installerPath, statusObj.logFilePath, statusObj.installStatusFilePath); }; // Later button click handler var laterBtnClicked = function () { HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_LATER, "autoUpdate", "installNotification", "cancel", "click" ); detachUpdateBarBtnHandlers(); setUpdateStateInJSON('updateInitiatedInPrevSession', false); }; //attaching UpdateBar handlers UpdateInfoBar.on(UpdateInfoBar.RESTART_BTN_CLICKED, restartBtnClicked); UpdateInfoBar.on(UpdateInfoBar.LATER_BTN_CLICKED, laterBtnClicked); UpdateInfoBar.showUpdateBar({ title: Strings.DOWNLOAD_COMPLETE, description: Strings.CLICK_RESTART_TO_UPDATE, needButtons: true }); setUpdateStateInJSON("autoUpdateInProgress", false); HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOADCOMPLETE_UPDATE_BAR_RENDERED, "autoUpdate", "installNotification", "render", "" ); }; if(!isAutoUpdateInitiated) { isAutoUpdateInitiated = true; updateJsonHandler.refresh() .done(function() { setUpdateStateInJSON('downloadCompleted', true) .done(statusValidFn); }); } else { setUpdateStateInJSON('downloadCompleted', true) .done(statusValidFn); } } else { // Installer validation failed if (updateJsonHandler.get("downloadCompleted")) { // If this was a cached download, retry downloading updateJsonHandler.reset(); var statusInvalidFn = function () { downloadAttemptsRemaining = MAX_DOWNLOAD_ATTEMPTS; getLatestInstaller(); }; setUpdateStateInJSON('downloadCompleted', false) .done(statusInvalidFn); } else { // If this is a new download, prompt the message on update bar var descriptionMessage = "", analyticsDescriptionMessage = ""; switch (statusObj.err) { case _nodeErrorMessages.CHECKSUM_DID_NOT_MATCH: descriptionMessage = Strings.CHECKSUM_DID_NOT_MATCH; analyticsDescriptionMessage = "Checksum didn't match."; break; case _nodeErrorMessages.INSTALLER_NOT_FOUND: descriptionMessage = Strings.INSTALLER_NOT_FOUND; analyticsDescriptionMessage = "Installer not found."; break; } HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_FAILED, "autoUpdate", "download", "fail", analyticsDescriptionMessage ); UpdateInfoBar.showUpdateBar({ type: "error", title: Strings.VALIDATION_FAILED, description: descriptionMessage }); setUpdateStateInJSON("autoUpdateInProgress", false); } } }
javascript
{ "resource": "" }
q16894
train
function () { // Restart button click handler var restartBtnClicked = function () { HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_RESTART, "autoUpdate", "installNotification", "installNow ", "click" ); detachUpdateBarBtnHandlers(); initiateUpdateProcess(statusObj.installerPath, statusObj.logFilePath, statusObj.installStatusFilePath); }; // Later button click handler var laterBtnClicked = function () { HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_LATER, "autoUpdate", "installNotification", "cancel", "click" ); detachUpdateBarBtnHandlers(); setUpdateStateInJSON('updateInitiatedInPrevSession', false); }; //attaching UpdateBar handlers UpdateInfoBar.on(UpdateInfoBar.RESTART_BTN_CLICKED, restartBtnClicked); UpdateInfoBar.on(UpdateInfoBar.LATER_BTN_CLICKED, laterBtnClicked); UpdateInfoBar.showUpdateBar({ title: Strings.DOWNLOAD_COMPLETE, description: Strings.CLICK_RESTART_TO_UPDATE, needButtons: true }); setUpdateStateInJSON("autoUpdateInProgress", false); HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOADCOMPLETE_UPDATE_BAR_RENDERED, "autoUpdate", "installNotification", "render", "" ); }
javascript
{ "resource": "" }
q16895
train
function () { HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_COMPLETE_USER_CLICK_RESTART, "autoUpdate", "installNotification", "installNow ", "click" ); detachUpdateBarBtnHandlers(); initiateUpdateProcess(statusObj.installerPath, statusObj.logFilePath, statusObj.installStatusFilePath); }
javascript
{ "resource": "" }
q16896
handleDownloadFailure
train
function handleDownloadFailure(message) { console.log("AutoUpdate : Download of latest installer failed in Attempt " + (MAX_DOWNLOAD_ATTEMPTS - downloadAttemptsRemaining) + ".\n Reason : " + message); if (downloadAttemptsRemaining) { // Retry the downloading attemptToDownload(); } else { // Download could not completed, all attempts exhausted enableCheckForUpdateEntry(true); UpdateStatus.cleanUpdateStatus(); var descriptionMessage = "", analyticsDescriptionMessage = ""; if (message === _nodeErrorMessages.DOWNLOAD_ERROR) { descriptionMessage = Strings.DOWNLOAD_ERROR; analyticsDescriptionMessage = "Error occurred while downloading."; } else if (message === _nodeErrorMessages.NETWORK_SLOW_OR_DISCONNECTED) { descriptionMessage = Strings.NETWORK_SLOW_OR_DISCONNECTED; analyticsDescriptionMessage = "Network is Disconnected or too slow."; } HealthLogger.sendAnalyticsData( autoUpdateEventNames.AUTOUPDATE_DOWNLOAD_FAILED, "autoUpdate", "download", "fail", analyticsDescriptionMessage ); UpdateInfoBar.showUpdateBar({ type: "error", title: Strings.DOWNLOAD_FAILED, description: descriptionMessage }); setUpdateStateInJSON("autoUpdateInProgress", false); } }
javascript
{ "resource": "" }
q16897
registerBracketsFunctions
train
function registerBracketsFunctions() { functionMap["brackets.notifyinitializationComplete"] = handleInitializationComplete; functionMap["brackets.showStatusInfo"] = showStatusInfo; functionMap["brackets.notifyDownloadSuccess"] = handleDownloadSuccess; functionMap["brackets.showErrorMessage"] = showErrorMessage; functionMap["brackets.notifyDownloadFailure"] = handleDownloadFailure; functionMap["brackets.notifySafeToDownload"] = handleSafeToDownload; functionMap["brackets.notifyvalidationStatus"] = handleValidationStatus; functionMap["brackets.notifyInstallationStatus"] = handleInstallationStatus; ProjectManager.on("beforeProjectClose beforeAppClose", _handleAppClose); }
javascript
{ "resource": "" }
q16898
inlineProvider
train
function inlineProvider(hostEditor, pos) { var jsonFile, propInfo, propQueue = [], // priority queue of propNames to try langId = hostEditor.getLanguageForSelection().getId(), supportedLangs = { "css": true, "scss": true, "less": true, "html": true }, isQuickDocAvailable = langId ? supportedLangs[langId] : -1; // fail if langId is falsy // Only provide docs when cursor is in supported language if (!isQuickDocAvailable) { return null; } // Send analytics data for Quick Doc open HealthLogger.sendAnalyticsData( "cssQuickDoc", "usage", "quickDoc", "open" ); // Only provide docs if the selection is within a single line var sel = hostEditor.getSelection(); if (sel.start.line !== sel.end.line) { return null; } if (langId === "html") { // HTML jsonFile = "html.json"; propInfo = HTMLUtils.getTagInfo(hostEditor, sel.start); if (propInfo.position.tokenType === HTMLUtils.ATTR_NAME && propInfo.attr && propInfo.attr.name) { // we're on an HTML attribute (and not on its value) propQueue.push(propInfo.attr.name.toLowerCase()); } if (propInfo.tagName) { // we're somehow on an HTML tag (no matter where exactly) propInfo = propInfo.tagName.toLowerCase(); propQueue.push("<" + propInfo + ">"); } } else { // CSS-like language jsonFile = "css.json"; propInfo = CSSUtils.getInfoAtPos(hostEditor, sel.start); if (propInfo.name) { propQueue.push(propInfo.name); // remove possible vendor prefixes propQueue.push(propInfo.name.replace(/^-(?:webkit|moz|ms|o)-/, "")); } } // Are we on a supported property? (no matter if info is available for the property) if (propQueue.length) { var result = new $.Deferred(); // Load JSON file if not done yet getDocs(jsonFile) .done(function (docs) { // Construct inline widget (if we have docs for this property) var displayName, propDetails, propName = _.find(propQueue, function (propName) { // find the first property where info is available return docs.hasOwnProperty(propName); }); if (propName) { propDetails = docs[propName]; displayName = propName.substr(propName.lastIndexOf("/") + 1); } if (propDetails) { var inlineWidget = new InlineDocsViewer(displayName, propDetails); inlineWidget.load(hostEditor); result.resolve(inlineWidget); } else { result.reject(); } }) .fail(function () { result.reject(); }); return result.promise(); } else { return null; } }
javascript
{ "resource": "" }
q16899
getHealthData
train
function getHealthData() { var result = new $.Deferred(), oneTimeHealthData = {}; oneTimeHealthData.snapshotTime = Date.now(); oneTimeHealthData.os = brackets.platform; oneTimeHealthData.userAgent = window.navigator.userAgent; oneTimeHealthData.osLanguage = brackets.app.language; oneTimeHealthData.bracketsLanguage = brackets.getLocale(); oneTimeHealthData.bracketsVersion = brackets.metadata.version; $.extend(oneTimeHealthData, HealthLogger.getAggregatedHealthData()); HealthDataUtils.getUserInstalledExtensions() .done(function (userInstalledExtensions) { oneTimeHealthData.installedExtensions = userInstalledExtensions; }) .always(function () { HealthDataUtils.getUserInstalledTheme() .done(function (bracketsTheme) { oneTimeHealthData.bracketsTheme = bracketsTheme; }) .always(function () { var userUuid = PreferencesManager.getViewState("UUID"); var olderUuid = PreferencesManager.getViewState("OlderUUID"); if (userUuid && olderUuid) { oneTimeHealthData.uuid = userUuid; oneTimeHealthData.olderuuid = olderUuid; return result.resolve(oneTimeHealthData); } else { // So we are going to get the Machine hash in either of the cases. if (appshell.app.getMachineHash) { appshell.app.getMachineHash(function (err, macHash) { var generatedUuid; if (err) { generatedUuid = uuid.v4(); } else { generatedUuid = macHash; } if (!userUuid) { // Could be a new user. In this case // both will remain the same. userUuid = olderUuid = generatedUuid; } else { // For existing user, we will still cache // the older uuid, so that we can improve // our reporting in terms of figuring out // the new users accurately. olderUuid = userUuid; userUuid = generatedUuid; } PreferencesManager.setViewState("UUID", userUuid); PreferencesManager.setViewState("OlderUUID", olderUuid); oneTimeHealthData.uuid = userUuid; oneTimeHealthData.olderuuid = olderUuid; return result.resolve(oneTimeHealthData); }); } else { // Probably running on older shell, in which case we will // assign the same uuid to olderuuid. if (!userUuid) { oneTimeHealthData.uuid = oneTimeHealthData.olderuuid = uuid.v4(); } else { oneTimeHealthData.olderuuid = userUuid; } PreferencesManager.setViewState("UUID", oneTimeHealthData.uuid); PreferencesManager.setViewState("OlderUUID", oneTimeHealthData.olderuuid); return result.resolve(oneTimeHealthData); } } }); }); return result.promise(); }
javascript
{ "resource": "" }