-
Notifications
You must be signed in to change notification settings - Fork 2
/
extension.ts
953 lines (860 loc) · 38.5 KB
/
extension.ts
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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
import * as path from 'path'
import * as fs from 'fs'
import {
ExtensionContext, StatusBarAlignment, Disposable, DocumentSelector,
Uri, QuickPickItem, StatusBarItem, OutputChannel,
TextDocument, Diagnostic, DiagnosticCollection
} from 'vscode'
import { workspace, window, commands, languages, extensions } from 'vscode'
import {
LanguageClient, LanguageClientOptions, ServerOptions, TransportKind, DiagnosticSeverity
} from 'vscode-languageclient/node'
import {
GSLDocumentSymbolProvider,
GSLHoverProvider,
GSLDefinitionProvider,
GSLDocumentHighlightProvider,
GSLDocumentFormattingEditProvider
} from './gsl'
import { EAccessClient } from './gsl/eaccessClient'
import { GameTerminal } from './gsl/gameTerminal'
import {
ScriptCompileStatus,
ScriptError,
ScriptProperties,
ScriptCompileResults,
withEditorClient,
EditorClientInterface
} from './gsl/editorClient'
import { formatDate } from './gsl/util/dateUtil'
import { OutOfDateButtonManager } from './gsl/status_bar/scriptOutOfDateButton'
import { scriptNumberFromFileName } from './gsl/util/scriptUtil'
import { GSLX_AUTOMATIC_DOWNLOADS, GSLX_DEV_ACCOUNT, GSLX_DEV_CHARACTER, GSLX_DEV_INSTANCE, GSLX_DEV_PASSWORD, GSLX_DISABLE_LOGIN, GSLX_ENABLE_SCRIPT_SYNC_CHECKS, GSLX_NEW_INSTALL_FLAG, GSLX_SAVED_VERSION, GSL_LANGUAGE_ID } from './gsl/const'
import { FrozenScriptWarningManager } from './gsl/status_bar/frozenScriptWarning'
const rx_script_number = /^\d{1,5}$/
const rx_script_number_in_filename = /(\d+)\.gsl/
interface LastSeenScriptModification {
modifier: string
lastModifiedDate: Date
}
interface DownloadScriptResult {
scriptNumber: number
/** Local file system path of downloaded script */
scriptPath: string
/** Up-to-date script properties */
scriptProperties: ScriptProperties
/** Status for "/ss checkedit"; undefined if feature is disabled */
syncStatus: string | undefined
}
export class GSLExtension {
private static context: ExtensionContext
private static diagnostics: DiagnosticCollection
static init (context: ExtensionContext) {
this.context = context
this.diagnostics = languages.createDiagnosticCollection()
}
static getDownloadLocation (): string {
let extPath: any = null
let useWorkspaceFolder = workspace.getConfiguration(GSL_LANGUAGE_ID).get('downloadToWorkspace')
if (useWorkspaceFolder && workspace.workspaceFolders) {
extPath = workspace.workspaceFolders[0].uri.fsPath
} else {
extPath = workspace.getConfiguration(GSL_LANGUAGE_ID).get('downloadPath')
}
if (!extPath) {
let rootPath = path.resolve(__dirname, '../gsl')
if (!fs.existsSync(rootPath)) { // Directory doesn't exist
fs.mkdirSync(rootPath) // Create directory
}
extPath = path.resolve(__dirname, '../gsl/scripts')
}
if (!fs.existsSync(extPath)) { // Directory doesn't exist
fs.mkdirSync(extPath) // Create directory
}
return extPath
}
/** @returns path of newly downloaded script, or `undefined` if download failed */
static async downloadScript (
client: EditorClientInterface,
script: number | string,
): Promise<DownloadScriptResult> {
try {
// Get script properties, keeping editor open
const scriptProperties = await client.modifyScript(
script,
true
).catch((e: any) => {
throw new Error(`Failed to get script properties: ${e.message}`)
})
// Write file
const destinationPath = path.join(
this.getDownloadLocation(),
scriptProperties.path.split('/').pop()!
)
if (scriptProperties.new) {
fs.writeFileSync(destinationPath, "")
await client.exitModifyScript()
} else {
// Note that captureScript closes modifyScript
let content = await client.captureScript().catch((e) => {
throw new Error(`Failed to download script: ${e.message}`)
})
if (content) {
if (content.slice(-2) !== '\r\n') { content += '\r\n' }
fs.writeFileSync(destinationPath, content)
}
}
// Record script modification info
const scriptNumber = Number(
path.basename(destinationPath)
.match(rx_script_number_in_filename)![1]
)
if (Number.isNaN(scriptNumber)) throw new Error('Expected script number, not NaN')
this.recordScriptModification(
scriptNumber,
scriptProperties.modifier,
scriptProperties.lastModifiedDate,
)
let syncStatus = undefined
if (
workspace
.getConfiguration(GSL_LANGUAGE_ID)
.get(GSLX_ENABLE_SCRIPT_SYNC_CHECKS)
&& this.context.globalState.get(GSLX_DEV_INSTANCE) === 'GS4D'
&& this.matchesRemoteAccount(scriptProperties.modifier)
) {
syncStatus = await client.showScriptCheckStatus(
scriptNumber
).catch((e: any) => {
console.error('Failed to run show script check', e)
})
}
// Return results
return {
scriptNumber,
scriptProperties,
scriptPath: destinationPath,
syncStatus: syncStatus || undefined
}
}
catch (e) {
// We passed keepalive=true to `modifyScript`, so we need to make sure
// to exit the editor when something goes wrong.
await client.exitModifyScript()
throw e
}
}
static async uploadScript (
client: EditorClientInterface,
script: number,
document: TextDocument
): Promise<ScriptCompileResults | undefined> {
// Get script properties, keeping editor open
const scriptProperties = await client.modifyScript(script, true)
// Confirm upload if needed
const requiresConfirmation = GSLExtension.requiresUploadConfirmation(
script,
scriptProperties
)
if (requiresConfirmation) {
const confirmation = await window.showWarningMessage(
requiresConfirmation.prompt,
{ modal: true },
'Yes'
)
if (confirmation !== 'Yes') {
await client.exitModifyScript()
return
}
}
// Send script
const lines = new Array<string>()
for (let n = 0, nn = document.lineCount; n < nn; n++) {
lines.push(document.lineAt(n).text)
}
if (lines[lines.length - 1] !== '') { lines.push('') }
// Note that sendScript closes modifyScript
let compileResults = await client.sendScript(lines, scriptProperties.new)
// Verify success
if (compileResults.status === ScriptCompileStatus.Failed) {
const problems = compileResults.errorList.map((error: ScriptError) => {
const line = document.lineAt(error.line - 1)!
return new Diagnostic (line.range, error.message, DiagnosticSeverity.Error)
})
this.diagnostics.set(document.uri, problems)
return compileResults
}
this.diagnostics.clear()
// Record updated script properties
const newScriptProperties = await client.modifyScript(script)
this.recordScriptModification(
script,
newScriptProperties.modifier,
newScriptProperties.lastModifiedDate,
)
return compileResults
}
static async checkModifiedDate (client: EditorClientInterface, script: number): Promise<Date | undefined> {
try {
const output = await client.showScript(script)
if (!output || !output.lastModifiedDate) return
return output.lastModifiedDate
} catch (e) {
console.error(e)
throw new Error('Failed to get /ss output')
}
}
static requiresUploadConfirmation (
script: number,
newestProperties: ScriptProperties
): { prompt: string } | undefined {
if (newestProperties.new) return // New scripts don't need confirmation
const lastSeenMod = this.findLastSeenScriptModification(script)
let reasons = []
if (!lastSeenMod || !lastSeenMod.lastModifiedDate || !lastSeenMod.modifier) {
reasons.push(
`I haven't seen you download this script before. This could be because you downloaded the script prior`
+ ` to the safety guard being added. If you want to be extra safe, you can download the script from the`
+ ` server, compare it with your local copy, and then proceed. At that point I will not warn you again`
+ ` for this specific reason. You can also proceed now if you are confident that your local copy`
+ ` should overwrite the server copy.`
)
}
else if (
lastSeenMod.lastModifiedDate.toISOString()
!== newestProperties.lastModifiedDate.toISOString()
) {
reasons.push(
`It appears to have been edited since you last downloaded it.`
+ `\nLocal: ${formatDate(lastSeenMod.lastModifiedDate)}.`
+ `\nServer: ${formatDate(newestProperties.lastModifiedDate)}.`
)
}
const currentAccount = this.getAccountName()
if (!this.matchesRemoteAccount(newestProperties.modifier)) {
reasons.push(
"Someone else modified it last."
+ `\nLast Modifier: ${newestProperties.modifier}`
+ ` (on ${formatDate(newestProperties.lastModifiedDate)})`
+ `\nYou: ${currentAccount}`
)
}
return reasons.length === 0 ? undefined : {
prompt:
`Overwriting script ${script} requires confirmation for the following reason(s):\n\n`
+ reasons.join('\n\n')
+ `\n\nWould you like to upload this script anyway?`,
}
}
static recordScriptModification(
script: number,
modifier: string,
lastModifiedDate: Date
): void {
this.context.globalState.update(
this.scriptPropsKey(script),
{ modifier, lastModifiedDate: lastModifiedDate.toISOString() }
)
}
static findLastSeenScriptModification(
script: number
): LastSeenScriptModification | undefined {
const output = this.context.globalState.get<{
modifier: string;
lastModifiedDate: string;
}>(this.scriptPropsKey(script))
return output ? {
modifier: output.modifier,
lastModifiedDate: new Date(output.lastModifiedDate) // restore from ISO string
} : undefined
}
/** @returns key for storing script modification data */
private static scriptPropsKey(script: number): string {
return `script_properties.${script}`
}
static getAccountName(): string | undefined {
const name = this.context.globalState.get(GSLX_DEV_ACCOUNT)
if (!name) return
return `W_${name}`
}
/**
* @returns true if the local account name matches the given remote account
* name. Note that the server truncates account names to 12 characters, so
* this will return false positives in the case where account names exceed
* that count.
*/
static matchesRemoteAccount(remoteAccountName: string): boolean {
return this.getAccountName()?.startsWith(remoteAccountName) || false
}
}
interface QuickPickCommandItem extends QuickPickItem { name: string }
export class VSCodeIntegration {
private context: ExtensionContext
private downloadButton: StatusBarItem
private uploadButton: StatusBarItem
private gslButton: StatusBarItem
private frozenScriptWarning: StatusBarItem
/** Managed entirely by `OutOfDateButtonManager` */
private scriptOutOfDateButton: StatusBarItem
private commandList: Array<QuickPickCommandItem>
private outputChannel: OutputChannel
private gameTerminal?: GameTerminal
private loggingEnabled: boolean
private frozenScriptWarningManager: FrozenScriptWarningManager | undefined
private outOfDateButtonManager: OutOfDateButtonManager
constructor (context: ExtensionContext) {
this.context = context
this.downloadButton = window.createStatusBarItem(StatusBarAlignment.Left, 50)
this.uploadButton = window.createStatusBarItem(StatusBarAlignment.Left, 50)
this.gslButton = window.createStatusBarItem(StatusBarAlignment.Left, 50)
this.frozenScriptWarning = window.createStatusBarItem(StatusBarAlignment.Left, 6)
// Place out-of-date button as far to the right as possible, but left of status message
this.scriptOutOfDateButton = window.createStatusBarItem(StatusBarAlignment.Left, 5)
this.commandList = [
{ label: "Download Script", name: 'gsl.downloadScript' },
{ label: "Upload Script", name: 'gsl.uploadScript' },
{ label: "Check script modification date", name: 'gsl.checkDate' },
{ label: "List GSL Tokens", name: 'gsl.listTokens'},
{ label: "Show GSL extension output channel", name: 'gsl.showChannel' },
{ label: "Toggle output logging", name: 'gsl.toggleLogging' },
{ label: "Open development terminal", name: 'gsl.openTerminal' },
{ label: "Connect to development server", name: 'gsl.openConnection' },
{ label: "User Setup", name: 'gsl.userSetup' },
]
this.outputChannel = window.createOutputChannel("GSL Editor (debug)")
this.loggingEnabled = false
this.registerCommands()
this.initializeComponents()
// Watch active editor for files that are out-of-date relative to
// the server. If a stale file is seen, highlight the stale file
// button, subtly prompting the user to refresh the local copy.
this.outOfDateButtonManager = new OutOfDateButtonManager(
this.scriptOutOfDateButton,
this.withEditorClient.bind(this),
this.showDownloadedScript.bind(this),
this.context
)
this.context.subscriptions.push(this.outOfDateButtonManager.activate())
// Watch active editor for frozen files. Uses periodic polling.
if (this.context.globalState.get(GSLX_DEV_INSTANCE) === 'GS4D') {
this.frozenScriptWarningManager = new FrozenScriptWarningManager(
this.frozenScriptWarning,
this.withEditorClient.bind(this)
)
this.context.subscriptions.push(
this.frozenScriptWarningManager.activate()
)
}
else {
this.frozenScriptWarning.hide()
}
}
private initializeComponents () {
this.downloadButton.text = "$(cloud-download) Download"
this.downloadButton.command = 'gsl.downloadScript'
this.downloadButton.show()
this.uploadButton.text = "$(cloud-upload) Upload"
this.uploadButton.command = 'gsl.uploadScript'
this.uploadButton.show()
this.gslButton.text = "$(ruby) GSL"
this.gslButton.command = 'gsl.showCommands'
this.gslButton.show()
if (workspace.getConfiguration(GSL_LANGUAGE_ID).get('displayGameChannel')) {
this.outputChannel.show(true);
}
}
/* commands */
private async commandDownloadScript () {
const prompt = 'Script number or verb name to download?'
const input = await window.showInputBox({ prompt })
if (!input) { return }
const scriptOptions = input.replace(/\s/g, '').split(';')
const scriptList: Array<number|string> = []
for (let option of scriptOptions) {
if (option.indexOf('-') > -1) {
let [first, second] = option.split('-')
let low = parseInt(first)
let high = parseInt(second)
if (isNaN(low) || isNaN(high) || low > high) {
window.showErrorMessage("Invalid script range: " + option)
}
for (;low <= high;) { scriptList.push(low++) }
} else {
const script = Number(option)
if (isNaN(script)) {
scriptList.push(option)
} else {
scriptList.push(script)
}
}
}
let script: string | number | undefined = undefined
try {
await this.withEditorClient(async (client) => {
for (script of scriptList) {
const result = await GSLExtension.downloadScript(
client,
script
)
if (!result) continue
this.outOfDateButtonManager.renderButton({ state: 'hidden'})
await vsc?.showDownloadedScript(result)
}
})
}
catch (e: unknown) {
console.error(e as any)
const error = `Failed to download script ${script || scriptList[0]}`
window.showErrorMessage((e instanceof Error) ? `${error} (${e.message})` : error)
}
}
private async showDownloadedScript(result: DownloadScriptResult) {
const { scriptNumber, scriptPath, scriptProperties, syncStatus } = result
window.setStatusBarMessage(`Downloaded ${scriptPath}`, 5000)
if (
syncStatus
&& !syncStatus.match(/All instances in sync/i)
&& GSLExtension.matchesRemoteAccount(scriptProperties.modifier)
) {
window.showInformationMessage(
`s${scriptNumber} - instances out of sync - ${syncStatus.toLowerCase()}`
)
}
try {
// Stop monitoring while we open the document so we don't
// trigger an unnecessary download/check
this.outOfDateButtonManager.stopMonitoring()
await window.showTextDocument(
await workspace.openTextDocument(scriptPath),
{ preview: false }
)
this.outOfDateButtonManager.renderButton({state: 'hidden'})
}
finally {
this.outOfDateButtonManager.resumeMonitoring()
}
}
private async commandUploadScript () {
const document = window.activeTextEditor?.document
if (!document || !(document.languageId === GSL_LANGUAGE_ID)) {
return void window.showWarningMessage(
"Script upload requires an active GSL script editor"
)
}
if (document.isDirty) {
let result = false
let i = 0
while (result === false && i++ < 3) {
result = await document.save()
}
if (result === false) {
return void window.showErrorMessage(
"Failed to save active script editor before upload."
)
}
}
if (document.getText().match(/^\s*$/)) {
return void window.showErrorMessage('Cannot upload empty script')
}
// Infer script number
const inferredScriptNum = scriptNumberFromFileName(document.fileName)
let scriptNum: number
if (rx_script_number.test(inferredScriptNum) === false) {
const prompt = "Unable to parse script number from active editor file name."
const placeHolder = "Script number to upload as?"
const input = await window.showInputBox({ prompt, placeHolder })
if (!input || rx_script_number.test(input) === false) {
return void window.showErrorMessage("Invalid script number provided.")
}
scriptNum = Number(input)
} else {
scriptNum = Number(inferredScriptNum)
}
const uploadMessage = window.setStatusBarMessage(`Uploading Script...`, 60000)
await this.withEditorClient(async (client) => {
let compileResults: ScriptCompileResults | undefined
try {
// Send script
compileResults = await GSLExtension.uploadScript(
client,
scriptNum,
document
) // closes modifyScript
if (!compileResults) return
// Display compilation feedback
if (compileResults.status === ScriptCompileStatus.Failed) {
const {script, errors, warnings} = compileResults
window.showErrorMessage(
`Script ${script}: Compile failed; ${errors} error(s), ${warnings} warning(s).`
)
commands.executeCommand('workbench.actions.view.problems')
return
}
const {script, bytes, maxBytes} = compileResults
const bytesRemaining = maxBytes - bytes
const bytesMsg = `${bytes.toLocaleString()} bytes (${bytesRemaining.toLocaleString()} left)`
window.setStatusBarMessage(`Script ${script}: Compile OK; ${bytesMsg}`, 5000)
this.outOfDateButtonManager.renderButton({state: 'hidden'})
} catch (e) {
const error = `Failed to upload script ${inferredScriptNum}`
window.showErrorMessage((e instanceof Error) ? `${error} (${e.message})` : error)
console.error(e)
// We passed keepalive=true to `modifyScript`, so we need to make sure
// to exit the editor when something goes wrong.
await client.exitModifyScript()
}
finally {
uploadMessage.dispose()
}
})
}
private async commandShowCommands () {
const command = await window.showQuickPick(
this.commandList, { placeHolder: 'Select a command to execute.' }
)
if (command) { commands.executeCommand(command.name) }
}
private async commandCheckDate () {
if (!window.activeTextEditor || !window.activeTextEditor.document) {
return void window.showErrorMessage (
"You must have an open script before you can check its date."
)
}
let scriptNumber = path.basename(window.activeTextEditor.document.fileName)
scriptNumber = scriptNumber.replace(/\D+/g, '').replace(/^0+/,'')
const script = Number(scriptNumber)
await this.withEditorClient(async (client) => {
window.setStatusBarMessage(`Checking modification date for script ${script} ...`, 5000)
const date = await GSLExtension.checkModifiedDate(client, script)
if (!date) {
window.showErrorMessage(`Failed to find modification date for script ${script}`)
return
}
window.setStatusBarMessage(
`Script ${script} was last modified on ${date.toLocaleDateString()} at ${date.toLocaleTimeString()}`,
5000
)
})
}
private commandListTokens () {
let uri = Uri.file(path.resolve(__dirname, './syntaxes/tokens.md'))
commands.executeCommand('markdown.showPreview', uri)
}
private async commandToggleLogging () {
await this.withEditorClient(async (client) => {
this.loggingEnabled = !this.loggingEnabled
client.toggleLogging()
window.setStatusBarMessage(this.loggingEnabled ? 'Logging enabled.' : 'Logging disabled.', 5000)
})
}
private async commandUserSetup () {
let account = await window.showInputBox({ prompt: "PLAY.NET Account:", ignoreFocusOut: true })
if (!account) { return void window.showErrorMessage("No account name entered; aborting setup.") }
let password = await window.showInputBox({ prompt: "Password:", ignoreFocusOut: true, password: true })
if (!password) { return void window.showErrorMessage("No password entered; aborting setup.")}
/* capture rejected promises */
let error: Error | undefined
const captureError = (e: Error) => (error = e, void(0))
/* login */
const gameChoice = await EAccessClient.login(account, password, { name: /.*?development.*?/i }).catch(captureError)
if (!gameChoice) {
const message = error ? error.message : "Login failed?"
return void window.showErrorMessage(message)
}
/* pick a game */
const gamePickOptions = {
ignoreFocusOut: true, placeholder: "Select a game ..."
}
const game = await window.showQuickPick(
gameChoice.toNameList(), gamePickOptions
)
if (!game) {
gameChoice.cancel()
return void window.showErrorMessage("No game selected; aborting setup.")
}
const characterChoice = await gameChoice.select(gameChoice.pick(game)).catch(captureError)
if (!characterChoice) {
const message = error ? error.message : "Game select failed?"
gameChoice.cancel()
return void window.showErrorMessage(message)
}
/* pick a character */
const characterPickOptions = {
ignoreFocusOut: true, placeholder: "Select a character ..."
}
const character = await window.showQuickPick(
characterChoice.toNameList(), characterPickOptions
)
if (!character) {
characterChoice.cancel()
return void window.showErrorMessage("No character selected; aborting setup.")
}
const result = await characterChoice.select(characterChoice.pick(character)).catch(captureError)
if (!result) {
const message = error ? error.message : "Character select failed?"
return void window.showErrorMessage(message)
}
/* we now have the info we need to log into the same and save the details */
const { sal, loginDetails } = result
/* store all the details for automated login */
this.context.globalState.update(GSLX_DEV_ACCOUNT, loginDetails.account)
this.context.globalState.update(GSLX_DEV_INSTANCE, loginDetails.game)
this.context.globalState.update(GSLX_DEV_CHARACTER, loginDetails.character)
await this.context.secrets.store(GSLX_DEV_PASSWORD, password)
window.showInformationMessage('Credentials stored for login')
}
private async commandOpenConnection () {
const msg = window.setStatusBarMessage("Connecting to game...")
try {
await this.withEditorClient(() => {
window.setStatusBarMessage("Connected to game successfully", 5000)
})
} catch (e) {
console.error(e)
const error = "Failed to connect to game"
window.setStatusBarMessage(error, 5000)
window.showErrorMessage((e instanceof Error) ? `${error} (${e.message})` : error)
}
finally {
msg.dispose()
}
}
private async commandOpenTerminal () {
if (this.gameTerminal) {
this.gameTerminal.show(true)
return
}
try {
const localGameTerminal
= this.gameTerminal
= new GameTerminal (() => this.gameTerminal = undefined)
this.gameTerminal.show(true)
await this.withEditorClient((client) => {
if (localGameTerminal !== this.gameTerminal) return // stale
this.gameTerminal.bindClient(client)
})
}
catch (e) {
console.error(e)
window.setStatusBarMessage("Failed to bind terminal to game client", 5000)
}
}
private registerCommands () {
let subscription: Disposable
subscription = commands.registerCommand('gsl.downloadScript', this.commandDownloadScript, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.uploadScript', this.commandUploadScript, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.showCommands', this.commandShowCommands, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.checkDate', this.commandCheckDate, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.listTokens', this.commandListTokens, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.toggleLogging', this.commandToggleLogging, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.showChannel', this.showGameChannel, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.userSetup', this.commandUserSetup, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.openConnection', this.commandOpenConnection, this)
this.context.subscriptions.push(subscription)
subscription = commands.registerCommand('gsl.openTerminal', this.commandOpenTerminal, this)
this.context.subscriptions.push(subscription)
}
/* public api */
getGameInstance (): string | undefined {
return this.context.globalState.get(GSLX_DEV_INSTANCE)
}
appendLineToGameChannel (text: string) {
this.outputChannel.appendLine(text)
}
showGameChannel () {
this.outputChannel.show(true)
}
outputGameChannel (text: string) {
this.outputChannel.appendLine(text)
}
async promptUserSetup () {
const message = "To start using the GSL Editor, you must run the User Setup process to store your Play.net account credentials."
const option = 'Start User Setup'
const choice = await window.showInformationMessage(message, option)
if (choice === option) {
this.commandUserSetup()
}
}
async checkForNewInstall () {
let flag = this.context.globalState.get(GSLX_NEW_INSTALL_FLAG)
if (flag !== true) {
const message = "For the best experience, the GSL Vibrant theme is recommended for the GSL Editor."
const option = 'Apply Theme'
const choice = await window.showInformationMessage(message, option)
if (choice === option) {
await workspace.getConfiguration().update('workbench.colorTheme', 'GSL Vibrant', true)
}
this.context.globalState.update(GSLX_NEW_INSTALL_FLAG, true)
}
}
async checkForUpdatedVersion () {
let extension = extensions.getExtension('patricktrant.gsl')
if (extension) {
let { packageJSON: { version } } = extension
let savedVersion = this.context.globalState.get(GSLX_SAVED_VERSION)
if (savedVersion && (savedVersion !== version)) {
const message = `The GSL Editor extension has been updated to version ${version}!`
const option = 'Show Release Notes'
const choice = await window.showInformationMessage(message, option)
if (choice === option) {
const changelogPath = path.resolve(__dirname, './CHANGELOG.md')
commands.executeCommand('markdown.showPreview', Uri.file(changelogPath))
}
this.copySpellCheckFiles()
this.context.globalState.update(GSLX_SAVED_VERSION, version)
}
}
}
async copySpellCheckFiles () {
let copyFile = false
let sourceFile = path.resolve(__dirname, './spellcheck/cspell.json')
let destinationFile = path.join(GSLExtension.getDownloadLocation(), 'cspell.json')
if (!fs.existsSync(destinationFile)) {
copyFile = true
} else if (fs.statSync(sourceFile).mtime > fs.statSync(destinationFile).mtime) {
copyFile = true
}
if (copyFile) {
fs.copyFile(sourceFile, destinationFile, () => {})
}
copyFile = false
sourceFile = path.resolve(__dirname, './spellcheck/GemStoneDictionary.txt')
destinationFile = path.join(GSLExtension.getDownloadLocation(), 'GemStoneDictionary.txt')
if (!fs.existsSync(destinationFile)) {
copyFile = true
} else if (fs.statSync(sourceFile).mtime > fs.statSync(destinationFile).mtime) {
copyFile = true
}
if (copyFile) {
fs.copyFile(sourceFile, destinationFile, () => {})
}
}
/**
* Provides an `EditorClient` object that is guaranteed to be exclusively owned
* by the caller, so long as all other callers are using this function. This
* prevents callers from sending conflicting commands to the game. If the user
* hasn't provided their login information yet this will skip execution of `task`
* and instead prompt the user to provide that login info. This wraps another
* function of the same name for convienence of ensuring preconditions and
* passing common parameters.
*/
async withEditorClient <T>(
task: (client: EditorClientInterface) => T
): Promise<T | undefined> {
if (workspace.getConfiguration(GSL_LANGUAGE_ID).get(GSLX_DISABLE_LOGIN)) {
return void window.showErrorMessage("Game login is disabled")
}
const account = this.context.globalState.get<string>(GSLX_DEV_ACCOUNT)
const instance = this.context.globalState.get<string>(GSLX_DEV_INSTANCE)
const character = this.context.globalState.get<string>(GSLX_DEV_CHARACTER)
const password = await this.context.secrets.get(GSLX_DEV_PASSWORD)
if (!account || !instance || !character || !password) {
this.promptUserSetup()
return
}
/** Redirect console to output channel */
const consoleAdapter: { log: (...args: any) => void } = {
log: (...args: any) => {
this.outputChannel.append(`[console(log): ${args.join(' ')}]\r\n`)
}
}
return withEditorClient({
login: {
account,
instance,
character,
password,
},
console: consoleAdapter,
downloadLocation: GSLExtension.getDownloadLocation(),
loggingEnabled: this.loggingEnabled,
onCreate: (client) => {
this.gameTerminal?.bindClient(client)
},
}, task)
}
}
class ExtensionLanguageServer {
private context: ExtensionContext
private lspClient: LanguageClient
constructor (context: ExtensionContext) {
this.context = context
this.lspClient = this.startLanguageServer()
}
private startLanguageServer () {
const relativePath = path.join('gsl-language-server', 'out', 'server.js')
const module = this.context.asAbsolutePath(relativePath)
const options = { execArgv: [ '--nolazy', '--inspect=6009' ] }
const transport = TransportKind.ipc
const serverOptions: ServerOptions = {
run: { module, transport },
debug: { module, transport, options }
}
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: 'file', language: GSL_LANGUAGE_ID }],
synchronize: {
fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
}
}
const lspClient = new LanguageClient (
'gslLanguageServer',
'GSL Language Server',
serverOptions,
clientOptions
)
lspClient.start()
return lspClient
}
}
export let vsc: VSCodeIntegration | undefined = undefined
export function activate (context: ExtensionContext) {
vsc = new VSCodeIntegration (context)
// const els = new ExtensionLanguageServer (context)
EAccessClient.console = {
log: (...args: any) => { vsc!.outputGameChannel(args.join(' ')) }
}
EAccessClient.debug = false
GSLExtension.init(context)
const selector: DocumentSelector = { scheme: '*', language: GSL_LANGUAGE_ID }
let subscription: Disposable
subscription = languages.registerDocumentSymbolProvider(
selector, new GSLDocumentSymbolProvider()
)
context.subscriptions.push(subscription)
subscription = languages.registerHoverProvider(
selector,
new GSLHoverProvider(async (script: number) => {
const config = workspace.getConfiguration(GSL_LANGUAGE_ID)
if (!config.get(GSLX_AUTOMATIC_DOWNLOADS)) return
return vsc?.withEditorClient(client => client.modifyScript(script))
})
)
context.subscriptions.push(subscription)
subscription = languages.registerDefinitionProvider(
selector,
new GSLDefinitionProvider(
!!workspace.getConfiguration(GSL_LANGUAGE_ID).get(GSLX_AUTOMATIC_DOWNLOADS)
)
)
context.subscriptions.push(subscription)
subscription = languages.registerDocumentHighlightProvider(
selector, new GSLDocumentHighlightProvider()
)
context.subscriptions.push(subscription)
subscription = languages.registerDocumentFormattingEditProvider(
selector, new GSLDocumentFormattingEditProvider()
)
context.subscriptions.push(subscription)
vsc.checkForNewInstall()
vsc.checkForUpdatedVersion()
}
export function deactivate () {
}