Repository navigation
Expand file tree
/
Copy pathExtensionManagerView.js
More file actions
549 lines (492 loc) · 26.2 KB
/
Copy pathExtensionManagerView.js
File metadata and controls
549 lines (492 loc) · 26.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2013 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/*unittests: ExtensionManager*/
/*global Phoenix*/
define(function (require, exports, module) {
var Strings = require("strings"),
EventDispatcher = require("utils/EventDispatcher"),
StringUtils = require("utils/StringUtils"),
ExtensionManager = require("extensibility/ExtensionManager"),
registry_utils = require("extensibility/registry_utils"),
NativeApp = require("utils/NativeApp"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager"),
ThemeManager = require("view/ThemeManager"),
DefaultDialogs = require("widgets/DefaultDialogs"),
Dialogs = require("widgets/Dialogs"),
InstallExtensionDialog = require("extensibility/InstallExtensionDialog"),
LocalizationUtils = require("utils/LocalizationUtils"),
LanguageManager = require("language/LanguageManager"),
Mustache = require("thirdparty/mustache/mustache"),
PathUtils = require("thirdparty/path-utils/path-utils"),
itemTemplate = require("text!htmlContent/extension-manager-view-item.html"),
PreferencesManager = require("preferences/PreferencesManager"),
DefaultExtensions = JSON.parse(require("text!extensions/default/DefaultExtensions.json")),
warnExtensionIDs = new Set(DefaultExtensions.warnExtensionStoreExtensions.extensionIDs),
Metrics = require("utils/Metrics");
/**
* Create a detached link element, so that we can use it later to extract url details like 'protocol'
*/
var _tmpLink = window.document.createElement('a');
/**
* Creates a view enabling the user to install and manage extensions. Must be initialized
* with initialize(). When the view is closed, dispose() must be called.
* @constructor
*/
function ExtensionManagerView() {
}
EventDispatcher.makeEventDispatcher(ExtensionManagerView.prototype);
/**
* Initializes the view to show a set of extensions.
* @param {ExtensionManagerViewModel} model Model object containing extension data to view
* @return {$.Promise} a promise that's resolved once the view has been initialized. Never
* rejected.
*/
ExtensionManagerView.prototype.initialize = function (model) {
var self = this,
result = new $.Deferred();
this.model = model;
this._itemTemplate = itemTemplate;
this._itemViews = {};
this.$el = $("<div class='extension-list tab-pane' id='" + this.model.source + "'/>");
this._$emptyMessage = $("<div class='empty-message'/>")
.appendTo(this.$el);
this._$infoMessage = $("<div class='info-message'/>")
.appendTo(this.$el).html(this.model.infoMessage);
this._$table = $("<table class='table'/>").appendTo(this.$el);
$(".sort-extensions").val(PreferencesManager.get("extensions.sort"));
this.model.initialize().done(function () {
self._setupEventHandlers();
}).always(function () {
self._render();
result.resolve();
});
return result.promise();
};
/**
* @type {jQueryObject}
* The root of the view's DOM tree.
*/
ExtensionManagerView.prototype.$el = null;
/**
* @type {Model}
* The view's model. Handles sorting and filtering of items in the view.
*/
ExtensionManagerView.prototype.model = null;
/**
* @type {jQueryObject}
* Element showing a message when there are no extensions.
*/
ExtensionManagerView.prototype._$emptyMessage = null;
/**
* @private
* @type {jQueryObject}
* The root of the table inside the view.
*/
ExtensionManagerView.prototype._$table = null;
/**
* @private
* @type {string} The compiled template we use for rendering items in the extension list.
*/
ExtensionManagerView.prototype._itemTemplate = null;
/**
* @private
* @type {Object.<string, jQueryObject>}
* The individual views for each item, keyed by the extension ID.
*/
ExtensionManagerView.prototype._itemViews = null;
/**
* Toggles between truncated and full length extension descriptions
* @param {string} id The id of the extension clicked
* @param {JQueryElement} $element The DOM element of the extension clicked
* @param {boolean} showFull true if full length description should be shown, false for shortened version.
*/
ExtensionManagerView.prototype._toggleDescription = function (id, $element, showFull) {
var description, linkTitle,
info = this.model._getEntry(id);
// Toggle between appropriate descriptions and link title,
// depending on if extension is installed or not
if (showFull) {
description = info.metadata.description;
linkTitle = Strings.VIEW_TRUNCATED_DESCRIPTION;
} else {
description = info.metadata.shortdescription;
linkTitle = Strings.VIEW_COMPLETE_DESCRIPTION;
}
$element.data("toggle-desc", showFull ? "trunc-desc" : "expand-desc")
.attr("title", linkTitle)
.prev(".ext-full-description").text(description);
};
/**
* @private
* Attaches our event handlers. We wait to do this until we've fully fetched the extension list.
*/
ExtensionManagerView.prototype._setupEventHandlers = function () {
const self = this,
originalTheme = ThemeManager.getCurrentTheme();
function _handleThemeChange(_event, theme) {
$(".current-theme-apply-hide").removeClass("current-theme-apply-hide");
$(`[data-extension-id="${theme.name}"].apply`).addClass("current-theme-apply-hide");
$(".currentThemeText").not(".forced-hidden").addClass("forced-hidden");
$(`[data-extension-id="${theme.name}"].currentThemeText`).removeClass("forced-hidden");
if(theme.name !== originalTheme.name){
$("#ThemeViewThemeRevert").removeClass("forced-hidden");
$("#InstalledViewThemeRevert").removeClass("forced-hidden");
} else {
$("#ThemeViewThemeRevert").addClass("forced-hidden");
$("#InstalledViewThemeRevert").addClass("forced-hidden");
}
}
ThemeManager.on(ThemeManager.EVENT_THEME_CHANGE, _handleThemeChange);
// Listen for model data and filter changes.
this.model
.on("filter", function () {
self._render();
})
.on("dispose", function () {
ThemeManager.off(ThemeManager.EVENT_THEME_CHANGE, _handleThemeChange);
})
.on("change", function (e, id) {
var extensions = self.model.extensions,
$oldItem = self._itemViews[id];
self._updateMessage();
if (self.model.filterSet.indexOf(id) === -1) {
// This extension is not in the filter set. Remove it from the view if we
// were rendering it previously.
if ($oldItem) {
$oldItem.remove();
delete self._itemViews[id];
}
} else {
// Render the item, replacing the old item if we had previously rendered it.
var $newItem = self._renderItem(extensions[id], self.model._getEntry(id));
if ($oldItem) {
$oldItem.replaceWith($newItem);
self._itemViews[id] = $newItem;
}
}
});
// UI event handlers
this.$el
.on("click", "a", function (e) {
var $target = $(e.target);
if ($target.hasClass("undo-remove")) {
ExtensionManager.markForRemoval($target.attr("data-extension-id"), false);
} else if ($target.hasClass("remove")) {
ExtensionManager.markForRemoval($target.attr("data-extension-id"), true);
} else if ($target.hasClass("undo-update")) {
ExtensionManager.removeUpdate($target.attr("data-extension-id"));
} else if ($target.hasClass("undo-disable")) {
ExtensionManager.markForDisabling($target.attr("data-extension-id"), false);
} else if ($target.data("toggle-desc") === "expand-desc") {
this._toggleDescription($target.attr("data-extension-id"), $target, true);
} else if ($target.data("toggle-desc") === "trunc-desc") {
this._toggleDescription($target.attr("data-extension-id"), $target, false);
} else if ($target.hasClass("theme_settings")) {
CommandManager.execute(Commands.CMD_THEMES_OPEN_SETTINGS);
}
}.bind(this))
.on("click", "button.install", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "install");
self._installUsingDialog($(e.target).attr("data-extension-id"));
})
.on("click", "button.update", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "update");
self._installUsingDialog($(e.target).attr("data-extension-id"), true);
})
.on("click", "button.undoTheme", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "undoTheme");
$("#ThemeViewThemeRevert").addClass("forced-hidden");
$("#InstalledViewThemeRevert").addClass("forced-hidden");
ThemeManager.setCurrentTheme(originalTheme.name);
e.preventDefault();
e.stopPropagation();
})
.on("click", "button.createTheme", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "createTheme");
NativeApp.openURLInDefaultBrowser("https://github.com/phcode-dev/theme-template");
e.preventDefault();
e.stopPropagation();
})
.on("click", "button.createExtesnion", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "createExtension");
NativeApp.openURLInDefaultBrowser("https://github.com/phcode-dev/extension-template");
e.preventDefault();
e.stopPropagation();
})
.on("click", "button.remove", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "remove");
ExtensionManager.markForRemoval($(e.target).attr("data-extension-id"), true);
})
.on("click", "button.disable", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "disable");
ExtensionManager.markForDisabling($(e.target).attr("data-extension-id"), true);
})
.on("click", "button.enable", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "enable");
ExtensionManager.enable($(e.target).attr("data-extension-id"));
})
.on("click", "button.apply", function (e) {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "btnClick", "apply");
const themeID = $(e.target).attr("data-extension-id");
let themeApplied = ThemeManager.setCurrentTheme(themeID);
if(!themeApplied) {
Dialogs.showModalDialog(DefaultDialogs.DIALOG_ID_ERROR, Strings.THEMES_ERROR,
Strings.THEMES_ERROR_CANNOT_APPLY);
}
});
};
/**
* @private
* Renders the view for a single extension entry.
* @param {Object} entry The extension entry to render.
* @param {Object} info The extension's metadata.
* @return {jQueryObject} The rendered node as a jQuery object.
*/
ExtensionManagerView.prototype._renderItem = function (entry, info) {
// Create a Mustache context object containing the entry data and our helper functions.
// Start with the basic info from the given entry, either the installation info or the
// registry info depending on what we're listing.
var context = $.extend({}, info);
// Normally we would merge the strings into the context we're passing into the template,
// but since we're instantiating the template for every item, it seems wrong to take the hit
// of copying all the strings into the context, so we just make it a subfield.
context.Strings = Strings;
// Calculate various bools, since Mustache doesn't let you use expressions and interprets
// arrays as iteration contexts.
context.isInstalled = !!entry.installInfo;
context.failedToStart = (entry.installInfo && entry.installInfo.status === ExtensionManager.START_FAILED);
context.disabled = (entry.installInfo && entry.installInfo.status === ExtensionManager.DISABLED);
context.hasVersionInfo = !!info.versions;
if (entry.registryInfo) {
var latestVerCompatInfo = ExtensionManager.getCompatibilityInfo(entry.registryInfo, brackets.metadata.apiVersion);
context.isCompatible = latestVerCompatInfo.isCompatible;
context.requiresNewer = latestVerCompatInfo.requiresNewer;
context.isCompatibleLatest = latestVerCompatInfo.isLatestVersion;
if(entry.registryInfo.ownerRepo){
context.githubStarCount = entry.registryInfo.gihubStars || "0";
context.ownerRepo = entry.registryInfo.ownerRepo;
}
entry.registryInfo.isVerified = 0;
if(entry.registryInfo.ownershipVerifiedByGitHub){
context.verified = StringUtils.format(Strings.EXTENSION_VERIFIED_PUBLISHER,
entry.registryInfo.ownershipVerifiedByGitHub[0].replace("https://", ""));
context.verifiedURL = entry.registryInfo.ownershipVerifiedByGitHub[0];
entry.registryInfo.isVerified = 1;
}
if (!context.isCompatibleLatest) {
var installWarningBase = context.requiresNewer ? Strings.EXTENSION_LATEST_INCOMPATIBLE_NEWER : Strings.EXTENSION_LATEST_INCOMPATIBLE_OLDER;
context.installWarning = StringUtils.format(installWarningBase, entry.registryInfo.versions[entry.registryInfo.versions.length - 1].version, latestVerCompatInfo.compatibleVersion);
}
context.downloadCount = entry.registryInfo.totalDownloads;
} else {
// We should only get here when viewing the Installed tab and some extensions don't exist in the registry
// (or registry is offline). These flags *should* always be ignored in that scenario, but just in case...
context.isCompatible = context.isCompatibleLatest = true;
}
// Check if extension metadata contains localized content.
var lang = brackets.getLocale(),
shortLang = lang.split("-")[0];
if (info.metadata["package-i18n"]) {
[shortLang, lang].forEach(function (locale) {
if (info.metadata["package-i18n"].hasOwnProperty(locale)) {
// only overlay specific properties with the localized values
["title", "description", "homepage", "keywords"].forEach(function (prop) {
if (info.metadata["package-i18n"][locale].hasOwnProperty(prop)) {
info.metadata[prop] = info.metadata["package-i18n"][locale][prop];
}
});
}
});
}
if (info.metadata.description !== undefined) {
info.metadata.shortdescription = StringUtils.truncate(info.metadata.description, 200);
}
context.isMarkedForRemoval = ExtensionManager.isMarkedForRemoval(info.metadata.name);
context.isMarkedForDisabling = ExtensionManager.isMarkedForDisabling(info.metadata.name);
context.isMarkedForUpdate = ExtensionManager.isMarkedForUpdate(info.metadata.name);
var hasPendingAction = context.isMarkedForDisabling || context.isMarkedForRemoval || context.isMarkedForUpdate;
context.showInstallButton = (this.model.source === this.model.SOURCE_REGISTRY || this.model.source === this.model.SOURCE_THEMES) && !context.updateAvailable;
context.showUpdateButton = context.updateAvailable && !context.isMarkedForUpdate && !context.isMarkedForRemoval;
context.showApplyButton = !!context.metadata.theme && !context.disabled;
context.isCurrentTheme = entry.installInfo &&
(entry.installInfo.metadata.name === ThemeManager.getCurrentTheme().name);
context.defaultFeature = warnExtensionIDs.has(info.metadata.name);
context.isDeprecatedExtension = ExtensionManager.isExtensionTakenDown(info.metadata.name);
context.allowInstall = context.isCompatible && !context.isInstalled;
if (Array.isArray(info.metadata.i18n) && info.metadata.i18n.length > 0) {
context.translated = true;
context.translatedLangs =
info.metadata.i18n.map(function (value) {
if (value === "root") {
value = "en";
}
return { name: LocalizationUtils.getLocalizedLabel(value), locale: value };
})
.sort(function (lang1, lang2) {
// List users language first
var locales = [lang1.locale, lang2.locale],
userLangIndex = locales.indexOf(lang);
if (userLangIndex > -1) {
return userLangIndex;
}
userLangIndex = locales.indexOf(shortLang);
if (userLangIndex > -1) {
return userLangIndex;
}
return lang1.name.localeCompare(lang2.name);
})
.map(function (value) {
return value.name;
})
.join(", ");
context.translatedLangs = StringUtils.format(Strings.EXTENSION_TRANSLATED_LANGS, context.translatedLangs);
// If the selected language is System Default, match both the short (2-char) language code
// and the long one
var translatedIntoUserLang =
(brackets.isLocaleDefault() && info.metadata.i18n.indexOf(shortLang) > -1) ||
info.metadata.i18n.indexOf(lang) > -1;
context.extensionTranslated = StringUtils.format(
translatedIntoUserLang ? Strings.EXTENSION_TRANSLATED_USER_LANG : Strings.EXTENSION_TRANSLATED_GENERAL,
info.metadata.i18n.length
);
}
var isInstalledInUserFolder = (entry.installInfo && entry.installInfo.locationType === ExtensionManager.LOCATION_USER);
context.allowRemove = isInstalledInUserFolder;
context.allowUpdate = context.showUpdateButton && context.isCompatible && context.updateCompatible && isInstalledInUserFolder;
if (!context.allowUpdate) {
context.updateNotAllowedReason = isInstalledInUserFolder ? Strings.CANT_UPDATE : Strings.CANT_UPDATE_DEV;
}
context.removalAllowed = context.isInstalled &&
!context.failedToStart && !hasPendingAction;
var isDefaultOrInstalled = this.model.source === "default" || this.model.source === "installed";
var isDefaultAndTheme = this.model.source === "default" && context.metadata.theme;
context.disablingAllowed = isDefaultOrInstalled && !isDefaultAndTheme && !context.disabled
&& !hasPendingAction && !context.metadata.theme && !context.isDeprecatedExtension;
context.enablingAllowed = isDefaultOrInstalled && !isDefaultAndTheme && context.disabled
&& !hasPendingAction && !context.metadata.theme && !context.isDeprecatedExtension;
// Copy over helper functions that we share with the registry app.
["lastVersionDate", "authorInfo"].forEach(function (helper) {
context[helper] = registry_utils[helper];
});
// Do some extra validation on homepage url to make sure we don't end up executing local binary
if (context.metadata.homepage) {
var parsed = PathUtils.parseUrl(context.metadata.homepage);
// We can't rely on path-utils because of known problems with protocol identification
// Falling back to Browsers protocol identification mechanism
_tmpLink.href = context.metadata.homepage;
// Check if the homepage refers to a local resource
if (_tmpLink.protocol === "file:") {
var language = LanguageManager.getLanguageForExtension(parsed.filenameExtension.replace(/^\./, ''));
// If identified language for the local resource is binary, don't list it
if (language && language.isBinary()) {
delete context.metadata.homepage;
}
}
}
return $(Mustache.render(this._itemTemplate, context));
};
/**
* @private
* Display an optional message (hiding the extension list if displayed)
* @return {boolean} Returns true if a message is displayed
*/
ExtensionManagerView.prototype._updateMessage = function () {
if (this.model.message) {
this._$emptyMessage.css("display", "block");
this._$emptyMessage.html(this.model.message);
this._$infoMessage.css("display", "none");
this._$table.css("display", "none");
return true;
}
this._$emptyMessage.css("display", "none");
this._$infoMessage.css("display", this.model.infoMessage ? "block" : "none");
this._$table.css("display", "");
return false;
};
/**
* @private
* Renders the extension entry table based on the model's current filter set. Will create
* new items for entries that haven't yet been rendered, but will not re-render existing items.
*/
ExtensionManagerView.prototype._render = function () {
var self = this;
this._$table.empty();
this._updateMessage();
this.model.filterSet.forEach(function (id) {
var $item = self._itemViews[id];
if (!$item) {
$item = self._renderItem(self.model.extensions[id], self.model._getEntry(id));
self._itemViews[id] = $item;
}
$item.appendTo(self._$table);
});
this.trigger("render");
};
/**
* @private
* Install the extension with the given ID using the install dialog.
* @param {string} id ID of the extension to install.
*/
ExtensionManagerView.prototype._installUsingDialog = function (id, _isUpdate) {
var entry = this.model.extensions[id];
const self = this;
if (entry && entry.registryInfo) {
const compatInfo = ExtensionManager.getCompatibilityInfo(entry.registryInfo, brackets.metadata.apiVersion),
url = ExtensionManager.getExtensionURL(id, compatInfo.compatibleVersion),
versionToInstall = entry.registryInfo.metadata.version;
fetch(`https://publish.phcode.dev/countDownload?extensionName=${id}&extensionVersion=${versionToInstall}`)
.catch(console.error);
// TODO: this should set .done on the returned promise
if (_isUpdate) {
// save to metric id as it is from public extension store.
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "update", id);
InstallExtensionDialog.updateUsingDialog(url).done((installResult)=>{
if(Phoenix.isNativeApp) {
// in tauri, due to browser cache for asset urls, updates to extensions will still load old
// extension through the http cache. So we show a restart app for the update to take effect
// message.
entry.installInfo.metadata = entry.registryInfo.metadata;
self.model._getEntry(id).updateAvailable = false;
// this is a hack as we will drop this extnsion manager and move to new one. so this will do.
self.model.trigger("change", id);
Dialogs.showInfoDialog(
Strings.EXTENSION_UPDATE_RESTART_TITLE,
Strings.EXTENSION_UPDATE_RESTART_MESSAGE
);
}
ExtensionManager.updateFromDownload(installResult);
});
} else {
Metrics.countEvent(Metrics.EVENT_TYPE.EXTENSIONS, "install", id);
InstallExtensionDialog.installUsingDialog(url);
}
}
};
/**
* Filters the contents of the view.
* @param {string} query The query to filter by.
*/
ExtensionManagerView.prototype.filter = function (query) {
this.model.filter(query);
};
exports.ExtensionManagerView = ExtensionManagerView;
});