/
index.js
807 lines (743 loc) · 21.7 KB
/
index.js
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
'use babel';
import { CompositeDisposable, Disposable } from 'atom';
import { exec } from 'child_process';
import os from 'os';
import path from 'path';
import Toolbar from './ui/toolbar.jsx';
import Console from './ui/console.jsx';
import GenerateDialog from './ui/generateDialog.jsx';
import NewProjectDialog from './ui/newProjectDialog.jsx';
import LoginDialog from './ui/loginDialog.jsx';
import UpdatesDialog from './ui/updatesDialog.jsx';
import Appc from './appc';
import Project from './project';
import Update from './update';
import Utils from './utils';
import autoCompleteHelper from './providers/autoCompleteHelper';
import tiappAutoCompleteProvider from './providers/tiappAutoCompleteProvider';
import viewAutoCompleteProvider from './providers/viewAutoCompleteProvider';
import controllerAutoCompleteProvider from './providers/controllerAutoCompleteProvider';
import styleAutoCompleteProvider from './providers/styleAutoCompleteProvider';
import definitionsProvider from './providers/definitionsProvider';
import related from './related';
import { environment } from 'titanium-editor-commons';
export default {
/**
* Package configuration - displayed in package settings
*/
config: {
general: {
order: 1,
type: 'object',
title: 'General',
properties: {
appcCommandPath: {
type: 'string',
default: 'appc',
title: 'Path to \'appc\' command',
description: 'Set the full path to the `appc` command if Atom is unable to locate it. NOTE: Requires relaunch.',
order: 1
},
screenshotPath: {
type: 'string',
default: os.homedir(),
title: 'Path to store screenshots',
description: 'Set the full path where the screenshots are stored.',
order: 2
},
displayBuildCommandInConsole: {
type: 'boolean',
default: true,
title: 'Display build command in console',
description: 'The executed build command is written to the console to aid debugging. This will include password arguments.',
order: 3
},
generateAutoCompleteSuggestions: {
type: 'boolean',
default: false,
title: 'Regenerate auto-complete suggestions',
description: 'Generate auto-complete suggestions for currently selected Titanium SDK. NOTE: Requires relaunch.',
order: 4
},
showToolbar: {
type: 'boolean',
default: true,
title: 'Show Appcelerator toolbar',
description: 'Show or hide the Appcelerator top toolbar with all menu buttons.',
order: 5
}
}
},
project: {
order: 2,
type: 'object',
title: 'Project',
properties: {
defaultI18nLanguage: {
type: 'string',
default: 'en',
title: 'Default language for i18n auto-completion',
order: 5
}
}
},
build: {
order: 3,
type: 'object',
title: 'Build',
properties: {
distributionOutputDirectory: {
type: 'string',
default: 'dist',
title: 'Distribution build output directory',
description: 'For iOS ad-hoc and App Store and Google Play builds. Ensure this location has write permission.',
order: 3
}
}
},
codeTemplates: {
order: 4,
type: 'object',
title: 'Code Templates',
properties: {
tssClass: {
type: 'string',
default: '\\n\'.${text}\': {\\n}\\n', // eslint-disable-line no-template-curly-in-string
title: 'Style class (.) template',
order: 1,
},
tssId: {
type: 'string',
default: '\\n\'#${text}\': {\\n}\\n', // eslint-disable-line no-template-curly-in-string
title: 'Style ID (#) template',
order: 2
},
tssTag: {
type: 'string',
default: '\\n\'${text}\': {\\n}\\n', // eslint-disable-line no-template-curly-in-string
title: 'Style tag template',
order: 3
},
jsFunction: {
type: 'string',
default: '\\nfunction ${text}(e){\\n}\\n', // eslint-disable-line no-template-curly-in-string
title: 'Event handler function template',
order: 4
}
}
},
android: {
order: 5,
type: 'object',
title: 'Android',
properties: {
keystorePath: {
order: 1,
type: 'string',
default: '',
title: 'Keystore path'
},
keystoreAlias: {
order: 2,
type: 'string',
default: '',
title: 'Keystore alias'
}
}
}
},
/**
* Auto-complete provider(s)
*
* @returns {Array}
*/
provideAutoComplete() {
return [ tiappAutoCompleteProvider, viewAutoCompleteProvider, controllerAutoCompleteProvider, styleAutoCompleteProvider ];
},
/**
* Click-to-definition provider(s)
*
* @returns {Object}
*/
provideDefinitions() {
return definitionsProvider;
},
/**
* Activate package - called when package is initialized
*
* @param {Object} state serialized state
*/
activate(state) {
this.serializedState = state;
this.disposable = new CompositeDisposable();
this.projectDisposable = new CompositeDisposable();
this.loadProject();
this.disposable.add(
atom.commands.add('atom-workspace', {
'appc:new': () => {
this.openNewProjectDialog();
}
}),
atom.menu.add([ {
label: 'Packages',
submenu: [ {
label: 'Appcelerator Titanium',
submenu: [ {
type: 'separator'
}, {
label: 'New Titanium Project...',
command: 'appc:new'
} ]
} ]
} ]),
atom.project.onDidChangePaths(() => {
this.loadProject();
})
);
atom.menu.update();
Project.onModified(() => {
if (!this.toolbar) {
return;
}
this.toolbar.hud.display({
icon: Project.appIcon(),
text: Project.appName() + ' | ' + Project.sdk(),
default: true
});
this.toolbar.update();
});
},
/**
* Deactivate package - called when package is disabled
*/
deactivate() {
this.toolbar && this.toolbar.destroy();
this.console && this.console.destroy();
this.disposable.dispose();
this.projectDisposable.dispose();
},
/**
* Serialized state of package
*
* @returns {Object}
*/
serialize() {
return {
console: this.console ? this.console.serializedState() : {}
};
},
/**
* Load titanium project
*/
async loadProject() {
Project.load();
if (Project.isTitaniumApp || Project.isTitaniumModule) {
this.projectDisposable.add(
atom.commands.add('atom-workspace', {
'appc:build': () => {
if (Project.isTitaniumApp || Project.isTitaniumModule) {
this.runBuildCommand();
}
},
'appc:stop': () => {
this.stopBuildCommand();
},
'appc:console:toggle': () => {
this.console.toggle();
},
'appc:clean': () => {
if (Project.isTitaniumApp || Project.isTitaniumModule) {
this.runCleanCommand();
}
},
'appc:login': () => {
if (Project.isTitaniumApp || Project.isTitaniumModule) {
this.runLogin();
}
},
'appc:toolbar:toggle': {
displayName: 'Appc: Toggle Toolbar',
didDispatch: () => {
if (!this.toolbar) {
return;
}
this.toolbar.toggle();
}
},
'appc:update:refresh': () => {
this.checkForUpdates();
}
}),
atom.workspace.observeTextEditors(editor => {
if (editor.getPath() && path.basename(editor.getPath()) === 'tiapp.xml') {
const grammar = atom.grammars.grammarForScopeName('text.xml');
editor.setGrammar(grammar);
}
}),
new Disposable(() => {
atom.workspace.getPaneItems().forEach(item => {
if (item instanceof Toolbar || item instanceof Console) {
item.destroy();
}
});
}),
);
let keymap;
let menu;
if (Project.isTitaniumApp) {
keymap = require('./keymap/app');
menu = require('./menu/app');
this.projectDisposable.add(
atom.commands.add('atom-workspace', {
'appc:generate': () => this.openGenerateDialog(),
'appc:open-related-view': () => related.openRelatedFile('xml'),
'appc:open-related-style': () => related.openRelatedFile('tss'),
'appc:open-related-controller': () => related.openRelatedFile('js'),
'appc:open-or-close-related': () => related.toggleAllRelatedFiles(),
'appc:take-screenshot': () => this.takeScreenshot(),
'appc:updates': () => this.openUpdatesDialog(),
// 'appc:closeRelated': () => related.closeRelatedFiles({forceAllClose: true})
})
);
} else {
keymap = require('./keymap/module');
menu = require('./menu/module');
}
this.projectDisposable.add(
atom.keymaps.add('appcelerator-titanium', keymap),
atom.menu.add(menu.items)
);
if (!this.toolbar) {
this.toolbar = new Toolbar();
}
if (!this.console) {
this.console = new Console(this.serializedState.console);
}
atom.config.onDidChange('appcelerator-titanium.general.showToolbar', () => {
this.toolbar.toggle();
});
const text = (Project.isTitaniumApp) ? `${Project.appName()} | ${Project.sdk()}` : `${Project.appName()} | ${Project.platforms().map(platform => Utils.nameForPlatform(platform)).join(', ')}`;
this.toolbar.hud.display({
icon: Project.appIcon(),
text: text,
default: true
});
this.toolbar.hud.display({
text: 'Preparing...',
spinner: true
});
const setupTargets = () => {
autoCompleteHelper.generateAutoCompleteSuggestions();
if (os.platform() === 'darwin') {
this.toolbar.populateiOSTargets();
} else {
this.toolbar.populateAndroidTargets();
}
this.toolbar.update({ disableUI: false });
this.toolbar.hud.displayDefault();
this.checkForUpdates();
};
const { missing } = await environment.validateEnvironment();
if (missing.length) {
let message = 'You are missing the following required components for Titanium development:';
for (let i = 0; i < missing.length; i++) {
const product = missing[i];
if (i < missing.length - 1) {
message = `${message} ${product.name},`;
} else {
message = `${message} ${product.name}`;
}
}
message = `${message}. Without these components the package will be unusable.`;
const errorNotification = atom.notifications.addError(message, {
buttons: [
{
onDidClick: async () => {
errorNotification.dismiss();
const updateInfo = [];
for (const product of missing) {
updateInfo.push(await product.getInstallInfo());
}
await Update.installUpdates(updateInfo, this.toolbar);
Appc.getInfo(() => {
setupTargets();
});
},
text: 'Install'
}
],
dismissable: true,
});
} else {
Appc.getInfo(() => {
setupTargets();
});
}
} else {
if (this.toolbar) {
this.toolbar.destroy();
this.toolbar = null;
}
if (this.console) {
this.console.destroy();
this.console = null;
}
atom.keymaps.removeBindingsFromSource('appcelerator-titanium');
const menu = require('./menu/app');
atom.menu.remove(menu.items);
this.projectDisposable.dispose();
this.projectDisposable = new CompositeDisposable();
}
atom.menu.update();
},
/**
* Run selected build command
*/
runBuildCommand() {
if ((!Project.isTitaniumApp && !Project.isTitaniumModule) || this.checkLoginAndPrompt()) {
return;
}
const {
buildCommand,
platform,
platformName,
target,
targetName,
targetType,
iOSCodeSigning,
androidKeystore,
customArgs,
enableLiveview
} = this.toolbar.getState();
const logLevel = this.console.getLogLevel();
let message;
let args = {};
if (buildCommand === 'run') {
args = [
'--platform', platform,
'--target', targetType,
'--log-level', logLevel
];
if (enableLiveview) {
args.push('--liveview');
}
const projectPath = (Project.isTitaniumApp) ? atom.project.getPaths()[0] : Project.pathForPlatform(platform);
args.push('--project-dir', projectPath);
if (targetType !== 'ws-local') {
args.push('--device-id', target);
}
if (targetType === 'device' && platform === 'ios') {
if (!iOSCodeSigning.certificate || !iOSCodeSigning.provisioningProfile) {
atom.notifications.addError('iOS code signing required', { detail: 'Please select a certificate and provisioning profile.' });
this.toolbar.expand();
return;
}
args = args.concat([
'--developer-name', iOSCodeSigning.certificate,
'--pp-uuid', iOSCodeSigning.provisioningProfile
]);
}
message = `${platformName} ${targetType} ${targetName}`;
} else if (buildCommand === 'dist-adhoc' || buildCommand === 'dist-appstore' && platform === 'ios') {
if (!iOSCodeSigning.certificate || !iOSCodeSigning.provisioningProfile || iOSCodeSigning.provisioningProfile === '-') {
atom.notifications.addError('iOS code signing required', { detail: 'Please select a certificate and provisioning profile.' });
this.toolbar.expand();
return;
}
args = [
'--platform', platform,
'--project-dir', atom.project.getPaths()[0],
'--target', buildCommand,
'--distribution-name', iOSCodeSigning.certificate,
'--pp-uuid', iOSCodeSigning.provisioningProfile,
'--output-dir', Utils.distributionOutputDirectory(),
'--log-level', logLevel
];
message = (buildCommand === 'dist-adhoc') ? 'iOS ad-hoc' : 'iOS distribution';
} else if (buildCommand === 'dist-appstore' && platform === 'android') {
if (!androidKeystore.path || !androidKeystore.alias || !androidKeystore.password) {
atom.notifications.addError('Android keystore information required', { detail: 'Please provide keystore path, alias and password.' });
this.toolbar.expand();
return;
}
args = [
'--platform', platform,
'--project-dir', atom.project.getPaths()[0],
'--target', 'dist-playstore',
'--output-dir', Utils.distributionOutputDirectory(),
'--keystore', androidKeystore.path,
'--store-password', androidKeystore.password,
'--alias', androidKeystore.alias,
'--log-level', logLevel
];
if (androidKeystore.privateKeyPassword) {
args.push('--key-password', androidKeystore.privateKeyPassword);
}
message = 'Android distribution';
} else if (buildCommand === 'build') {
args = [
'--platform', platform,
'--project-dir', Project.pathForPlatform(platform),
'--log-level', logLevel,
'--build-only'
];
} else if (buildCommand === 'custom') {
args = customArgs.split(' ').concat([ '--project-dir', atom.project.getPaths()[0] ]);
// For custom args, check if the option was already appended previously and let the dev
// know that migration is recommended
if (enableLiveview) {
if (args.indexOf('--liveview') !== -1) {
atom.notifications.addError('Duplicate \'--liveview\' option', {
detail: 'LiveView option \'--liveview\' already appended by custom arguments, but enabled via UI as well. Skipping duplicate argument ...',
dismissable: true
});
} else {
args.push('--liveview');
}
}
}
const options = {
args: args,
log: (text) => {
this.console.write(text);
if (text.indexOf('Start simulator log') !== -1 || text.indexOf('Start application log') !== -1) {
this.toolbar.hud.display({
text: (buildCommand === 'custom') ? 'Running...' : `Running on ${message}`
});
}
if (text.indexOf('Appcelerator Login required to continue') !== -1) {
this.stopBuildCommand();
this.checkLoginAndPrompt();
}
},
error: (text) => {
this.console.write(text);
},
exit: (code) => {
if (code !== 0) {
this.console.error(`Build failed. Process exited with code ${code}.`);
}
this.toolbar.hud.displayDefault();
this.toolbar.update({ buildInProgress: false });
}
};
this.console.clear();
this.console.show(true);
this.toolbar.hud.display({
text: (buildCommand === 'custom') ? 'Building...' : `Building for ${message}`,
spinner: true
});
if (atom.config.get('appcelerator-titanium.general.displayBuildCommandInConsole')) {
this.console.write(`appc run ${options.args.join(' ')}`);
}
this.runProc = Appc.run(options);
this.toolbar.update({ buildInProgress: true });
},
/**
* Stop build command
*/
stopBuildCommand() {
if (!Project.isTitaniumApp && !Project.isTitaniumModule) {
return;
}
this.runProc.kill();
this.toolbar.hud.displayDefault();
this.toolbar.update({ buildInProgress: false });
},
/**
* Stop build command
*/
runCleanCommand() {
if (!Project.isTitaniumApp && !Project.isTitaniumModule) {
return;
}
const options = {
args: {},
log: (text) => {
this.console.write(text);
},
error: (text) => {
this.console.write(text);
},
exit: () => {
this.toolbar.hud.displayDefault();
this.toolbar.update({ buildInProgress: false });
}
};
this.console.clear();
this.console.show(true);
this.console.write('appc ti clean');
this.runProc = Appc.clean(options);
this.toolbar.update({ buildInProgress: true });
},
/**
* Run appc login
*/
runLogin() {
if (!Project.isTitaniumApp && !Project.isTitaniumModule) {
return;
}
let loginPanel;
this.loginDialog = new LoginDialog({
cancel: () => {
loginPanel.destroy();
},
callback: (args) => {
args.callback = () => {
loginPanel.destroy();
};
args.exit = () => {
loginPanel.destroy();
};
args.log = (out, proc) => {
if (out.toLowerCase().includes('invalid')) {
loginPanel.destroy();
atom.notifications.addError('Login error');
proc.kill();
} else if (out.toLowerCase().includes('this computer must be authorized')) {
loginPanel.destroy();
atom.notifications.addError('2FA is not supported in Atom currently, please login via Terminal.');
proc.kill();
} else if (out.toLowerCase().includes('into which organization')) {
loginPanel.destroy();
atom.notifications.addError('Organization selection is not supported in Atom currently, please login via Terminal.');
proc.kill();
} else if (out.toLowerCase().includes('logged in')) {
atom.notifications.addSuccess('Login successful');
}
};
args.error = () => {
atom.notifications.addError('Login error');
loginPanel.destroy();
};
Appc.login(args);
}
});
loginPanel = atom.workspace.addModalPanel({ item: this.loginDialog });
},
/**
* Take a screenshot of a device/simulator/emulator
*/
takeScreenshot() {
// If the UI is not ready, abort!
if (this.toolbar.state.disableUI) {
atom.notifications.addError('Please wait until the tooling has finished processing and try again!');
return;
}
// If the build command is not "run" or "custom", abort!
if (this.toolbar.state.buildCommand !== 'run' && this.toolbar.state.buildCommand !== 'custom') {
atom.notifications.addError('Screenshots can only be taken for the "Run" or "Custom" configuration');
return;
}
const filename = path.join(atom.config.get('appcelerator-titanium.general.screenshotPath'), 'screenshot_' + new Date().getTime() + '.png');
const hasAndroidDevices = (Appc.info.android.devices && Appc.info.android.devices.length > 0) || (Appc.info.android.emulators && Appc.info.android.emulators.length > 0);
// macOS is the only platform that can take build for iOS. Use it if the target platform is "ios"
if (os.platform() === 'darwin' && this.toolbar.state.platform === 'ios') {
// iOS
exec('xcrun simctl io booted screenshot ' + filename, (error, stdout, stderr) => {
if (error) {
atom.notifications.addError(`Cannot save iOS screenshot: ${stderr}`);
return;
}
atom.notifications.addSuccess(`iOS screenshot saved to: ${filename}`);
});
}
// Android screenshots can be taken is the target platform is "android" and there are devices available
if (this.toolbar.state.platform === 'android' && hasAndroidDevices) {
// Android
exec('adb shell /system/bin/screencap -p > ' + filename, (error, stdout, stderr) => {
if (error) {
atom.notifications.addError(`Cannot save Android screenshot: ${stderr}`);
return;
}
atom.notifications.addSuccess(`Android screenshot saved to: ${filename}`);
});
}
},
/**
* Display generate dialog
*/
openGenerateDialog() {
if (!Project.isTitaniumApp) {
return;
}
let generateDialogPanel;
this.generateDialog = new GenerateDialog({
cancel: () => {
generateDialogPanel.destroy();
},
generate: (type, args) => {
Appc.generate({
type,
args,
error: (err) => atom.notifications.addError(err.message, err)
});
generateDialogPanel.destroy();
}
});
generateDialogPanel = atom.workspace.addModalPanel({ item: this.generateDialog });
},
/**
* Display new project dialog
*/
openNewProjectDialog() {
if (this.checkLoginAndPrompt()) {
return;
}
let newProjectDialogPanel;
this.newProjectDialog = new NewProjectDialog({
cancel: () => {
newProjectDialogPanel.destroy();
},
callback: (args) => {
args.callback = () => {
newProjectDialogPanel.destroy();
};
Appc.new(args);
}
});
newProjectDialogPanel = atom.workspace.addModalPanel({ item: this.newProjectDialog });
},
/**
* Display Updates dialog
*/
openUpdatesDialog() {
let updatesDialogPanel;
this.updatesDialog = new UpdatesDialog({
cancel: () => {
updatesDialogPanel.destroy();
},
install: async (type, args) => {
updatesDialogPanel.destroy();
await Update.installUpdates(args, this.toolbar, true);
this.toolbar.hud.displayDefault();
}
});
updatesDialogPanel = atom.workspace.addModalPanel({ item: this.updatesDialog });
},
/**
* Check user is logged in and displays prompt if required. Returns true is prompted.
*
* @returns {Boolean}
*/
checkLoginAndPrompt() {
if (!Appc.isUserLoggedIn()) {
const terminal = (os.platform() === 'win32') ? 'Command Prompt' : 'Terminal';
atom.notifications.addError('Appcelerator Login Required', {
detail: `Open ${terminal} and run \`appc login\` command`,
dismissable: true
});
return true;
}
},
async checkForUpdates() {
const details = await Update.refresh();
if (details) {
this.toolbar.hud.update({
updates: true,
updateInfo: details
});
return details;
}
}
};