forked from ChatTheatre/orchil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorchil.js
2113 lines (2055 loc) · 74.3 KB
/
orchil.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
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
var conn, output, input, debugtrack, gameCharacter, generic, hasChars, http_port, skotosAttributes;
var macros;
var c = {};
//-----Protocol Code
function initAJAX(profile) {
conn = {
queue: [],
busy: false,
send: function (message) {
this.queue.push(message);
this.push();
},
push: function () {
if (this.busy != false) {
return false;
}
if (this.queue.length < 1) {
return false;
}
this.busy = this.queue[0];
this.queue.shift();
var x;
if (window.XMLHttpRequest) { //Normal browsers
x=new XMLHttpRequest();
} else { //IE5/6
x=new ActiveXObject('Microsoft.XMLHTTP');
}
x.onreadystatechange=function() {
if (x.readyState==4) {
if (x.status==200) {
debugMsg("<span style='color: blue;'>SAFE RESPONSE:</span> " + safe_tags_replace(x.responseText), "received");
doReceive(x.responseText);
conn.busy = false;
conn.push();
} else {
printScreened("<span style='color: red;'>ERROR:</span> HTTP code " + x.status, "connection error");
}
}
}
x.open("POST",profile.path, true);
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
x.send("m="+this.busy);
return this.busy;
}
};
printScreened("AJAX connection initialized.", "connection");
}
function initWebSocket(profile) {
c = profile;
if (conn) {
writeToConsole('Closing pre-existing connection.');
wsCloseIfOpen.close(1001, 'Closing previous connection.');
}
if (!window.WebSocket) {
printScreened("<span style='color: red;'>ERROR:</span> Your browser does not support WebSockets, or has them currently disabled.", "connection error");
return false;
}
if(profile.extra == "launcher") {
generic = true;
}
if(profile.chars == true) {
hasChars = true;
}
if(profile.http_port) http_port = profile.http_port;
var wsuri = profile.protocol + "://" + profile.server + ":" + profile.port + profile.path;
var wsuri = profile.protocol + "://" + profile.server + ":" + profile.port + profile.path;
printUnscreened("Starting connection to: " + wsuri, "connection debug");
try {
conn = new WebSocket(wsuri);
} catch (e) {
if(e.name === "SecurityError") {
printScreened("<span style='color: red;'>ERROR:</span> Your browser has blocked the connection according to its security rules. This might be caused by opening the client in an usual way. Please close this window and go to <a href='https://www.skotos.net/'>https://www.skotos.net/</a> to try again, or email <a href='mailto:[email protected]'>[email protected]</a> if this error persists.", "connection error");
} else {
printScreened("<span style='color: red;'>ERROR:</span> Your browser encountered an error while trying to connect. Please close this window and go to <a href='https://www.skotos.net/'>https://www.skotos.net/</a> to try again, or email <a href='mailto:[email protected]'>[email protected]</a> with the information below if this error persists.<br><br><span style='color: grey;'>Additional error info:<br>"+safe_tags_replace(e.name)+"<br>"+safe_tags_replace(e.message)+"</span>", "connection error");
}
return false;
}
//conn.binaryType = 'arraybuffer';
if (true) {
addEvent(conn, 'open', onWSOpen);
addEvent(conn, 'close', onWSClose);
addEvent(conn, 'message', onWSMessage);
addEvent(conn, 'error', onWSError);
} else {
conn.onopen = function(evt) { onWSOpen(evt) };
conn.onclose = function(evt) { onWSClose(evt) };
conn.onmessage = function(evt) { onWSMessage(evt) };
conn.onerror = function(evt) { onWSError(evt) };
}
}
function onWSOpen(evt) {
window.onbeforeunload = function(evt) { wsCloseIfOpen(4001, "Window unloading."); };
connConnected();
}
function onWSClose(evt) {
connDisconnected();
}
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function onWSMessage(evt) {
if (evt.data) {
if(evt.data instanceof Blob) {
wsProcessBlob(evt.data);
} else if(evt.data instanceof ArrayBuffer) {
wsProcessArrayBuffer(evt.data);
} else {
wsProcessText(evt.data);
}
} else {
debugMsg("<span style='color: blue;'>NO DATA IN RESPONSE</span> ", "received");
}
}
function wsProcessBlob(blb) {
var reader = new FileReader();
addEvent(reader, "loadend", function() {
doReceive(reader.result);
});
reader.readAsText(blb);
}
function wsProcessArrayBuffer(buf) {
writeToConsole("buffer");
doReceive(txt);
}
function wsProcessText(txt) {
writeToConsole(txt);
doReceive(txt);
}
function onWSError(evt) {
console.log(evt);
printScreened("<span style='color: red;'>WS ERROR:</span> The connection to the server encountered an error. There may be an issue with your internet connection, or the game server may be restarting or temporarily offline. You can wait a moment and try again, check your internet connection, or visit <a href='https://www.skotos.net/'>https://www.skotos.net/</a> and the forums to connfirm that the game server is up. <br><br><span style='color: grey;'>Additional error info:<br>"+safe_tags_replace(evt.name)+"<br>"+safe_tags_replace(evt.message)+"</span>", "connection error");
}
function wsCloseIfOpen(code, message) {
if (conn && conn.readyState < 2) {
conn.close(code, message);
}
}
//-----Generic Code
var tagsToReplace = {"&":"&", "<":"<", ">":">"};
function replaceTag(tag) {
return tagsToReplace[tag] || tag;
}
function safe_tags_replace(str) {
return typeof(str) === "string" ? str.replace(/[&<>]/g, replaceTag) : str;
}
function replaceBadMSCharacters(text) {
return text.replace(/[\u2018\u2019\u201A]/g, "\'").replace(/[\u201C\u201D\u201E]/g, "\"").replace(/\u2026/g, "...").replace(/[\u2013\u2014]/g, "-").replace(/\u02C6/g, "^").replace(/\u2039/g, "<").replace(/\u203A/g, ">").replace(/[\u02DC\u00A0]/g, " ");
}
function addEvent(obj, evType, fn, useCapture){
if (obj.addEventListener){
obj.addEventListener(evType, fn, useCapture);
} else if (obj.attachEvent){
obj.attachEvent("on"+evType, fn);
} else {
alert("Error attaching event: "+ obj + "; " + evType + "; " + fn + "; " + useCapture);
}
}
function removeEvent(obj, evType, fn, useCapture) {
if (obj.removeEventListener){
obj.removeEventListener(evType, fn, useCapture);
} else if (obj.detachEvent){
obj.detachEvent("on"+evType, fn);
} else {
console.log("Error detaching event.");
}
}
function debugMsg(text, format) {
console.log(text);
//printUnscreened(text, format + " debug");
}
function cancelEvent(e) {
e.noFixFocus = true;
e.stopPropagation ? e.stopPropagation() : (e.cancelBubble=true);
}
if (!Array.prototype.indexOf) {
//Defining this for IE8 and below
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
if ( !Date.prototype.toISOString ) {
//Defining this for IE8 and below
( function() {
function pad(number) {
var r = String(number);
if ( r.length === 1 ) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear()
+ '-' + pad( this.getUTCMonth() + 1 )
+ '-' + pad( this.getUTCDate() )
+ 'T' + pad( this.getUTCHours() )
+ ':' + pad( this.getUTCMinutes() )
+ ':' + pad( this.getUTCSeconds() )
+ '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
+ 'Z';
};
}() );
}
function addClass(node, cls) {
writeToConsole("+ old: "+node.ClassName+" adding: "+cls);
node.className = (node.ClassName?node.ClassName:"") + " " + cls;
writeToConsole("+ new: "+node.ClassName);
}
function removeClass(node, cls) {
writeToConsole("- old: "+node.ClassName+" removing: "+cls);
if(node && node.className && node.className.indexOf(cls) >= 0) {
var pattern = new RegExp('\\s*' + cls + '\\s*');
node.className = node.className.replace(pattern, ' ');
}
writeToConsole("- new: "+node.ClassName);
}
//-----UI Code
//-----Prefs and Init
var prefs;
var pref_options = {
arrow_behavior: {
cat: "control",
type: ["options"],
desc: "How the up/down arrow keys behave when the input box already has text.",
def: "always_scroll",
opt: {
always_scroll: "Pressing the Up or Down arrow keys by themselves will always scroll through your command history. (This is the behavior of the Alice client.)",
current_first: "Pressing the Up or Down arrow keys will take you to the beginnging or end of the current line; or, if you are already there, then scroll through your command history. The Ctrl key will force it to always scroll through your command history. (This is the behavior of the Zealotry client.)"
}
},
horizontal_scroll: {
cat: "layout",
type: ["options"],
desc: "Management of the horizontal scroll bar for the output window.",
def: "normal",
opt: {
normal: "The horizontal scroll bar is visible if you have any extra-long lines in your scrollback.",
force_wrap: "Extra long-lines are forced to wrap, even if it breaks formatting. Prevents horizontal scrollbars.",
force_chop: "Extra-long lines have the extra length chopped off (except in logs). Probably not a good idea. Prevents horizontal scrollbars.",
automatic: "The horizontal scroll bar is visible if your CURRENT view has any extra-long lines. (Except when scrolling up, in which case it is visible if anything in your scrollback needs it.)",
full_adaptive: "Same as automatic, but keeps working when you scroll up. May slow down client. Experimental. Not yet implemented."
},
onChange: function(old) {
var wrap = "pre";
var flow = "auto";
switch (prefs.horizontal_scroll) {
case "normal":
wrap = "pre";
flow = "auto";
break;
case "force_wrap":
wrap = "pre-wrap";
flow = "auto";
break;
case "force_chop":
wrap = "pre";
flow = "hidden";
//make output not have scrollbars
break;
case "automatic":
wrap = "pre";
flow = scrolledToBottom ? "hidden" : "auto";
break;
case "full_adaptive":
wrap = "pre";
flow = "hidden";
break;
}
wrap = "#output pre {white-space:" + wrap + ";}";
flow = "#output {overflow-x: " + flow + ";}";
cssMods.pre_wrap = setStyle(wrap+" "+flow,cssMods.pre_wrap);
if (old==="automatic") {
removeEvent(window, "resize", updateAutomaticScroll);
removeEvent(output, "scroll", updateAutomaticScroll);
} else if (old==="full_adaptive") {
removeEvent(window, "resize", updateAdaptiveScroll);
removeEvent(output, "scroll", updateAdaptiveScroll);
}
if (prefs.horizontal_scroll==="automatic") {
currentlyAdjustingScroll = false;
currentAdjustingMode = false;
updateAutomaticScroll();
addEvent(window, "resize", updateAutomaticScroll, {passive:true});
addEvent(output, "scroll", updateAutomaticScroll, {passive:true});
} else if (prefs.horizontal_scroll==="full_adaptive") {
currentlyAdjustingScroll = false;
currentAdjustingMode = false;
updateAdaptiveScroll();
addEvent(window, "resize", updateAdaptiveScroll, {passive:true});
addEvent(output, "scroll", updateAdaptiveScroll, {passive:true});
}
}
},
continuous_animations: {
cat: "styling",
type: ["options"],
desc: "What version to play of animations that stay for a while.",
def: "subtle_only",
dis: true,
opt: {
subtle_only: "Don't play strong/distracting versions of continuous animations, but do play subtle versions when available.",
subtle_preferred: "Play the subtle versions of continuous animated effects when available, or stronger versions if that'all that's available.",
bold_preferred: "Play the strongest, most animated and/or most distracting versions of continuous animations available.",
none: "Do not play continuous animated effects."
}
},
brief_animations: {
cat: "styling",
type: ["options"],
desc: "What version to play of animations that only appear for a moment.",
def: "subtle_preferred",
dis: true,
opt: {
subtle_only: "Don't play strong/distracting versions of brief animations, but do play subtle versions when available.",
subtle_preferred: "Play the subtle versions of brief animated effects when available, or stronger versions if that'all that's available.",
bold_preferred: "Play the strongest, most animated and/or most distracting versions of brief animations available.",
none: "Do not play brief animated effects."
}
},
command_history_lines: {
cat: "control",
type: ["integer", "nonnegative"],
desc: "Number of recent commands to remember for re-entry. High numbers may affect client lag.",
on0: "No limit",
def: 100,
onChange: function(old) { while(prefs.command_history_lines && commandHistory.length > prefs.command_history_lines) commandHistory.shift(); if (historyPosition > commandHistory.length) historyPosition = commandHistory.length;}
},
output_click: {
cat: "control",
type: ["options"],
desc: "Whether to snap the cursor to the input box when you click the output area.",
def: "focus_input",
opt: {
focus_input: "When the output area (scrollback) is clicked, keep the focus on the input box, so you can keep typing without needing to click the input box. Selecting text in the output area overrides this, putting focus on the output area (so that the text can be copied, etc.)",
focus_output: "When the output area (scrollback) is clicked, move focus to the output area. This disables typing until the input box is clicked or the tab key is pressed, but may make the text easier to interact with in some browsers."
}
},
scrollback_count: {
cat: "layout",
type: ["integer", "nonnegative"],
desc: "Number of 'elements' (lines) to keep in scrollback. Very high numbers may affect client lag after extended play.",
def: 0,
on0: "No limit",
onChange: function(old) { while(prefs.scrollback_count && output.childNodes.length > prefs.scrollback_count) output.removeChild(output.firstChild);}
},
local_echo: {
cat: "layout",
type: ["options"],
desc: "Whether to show the commands you type, in the output area after you send them.",
def: "on",
opt: {
on: "Commands you type appear in the output area after you send them.",
off: "Commands you type are not shown at all after you send them.",
temporary: "Commands you type are shown after sending them, until something new is received from the server. This makes the command visible if there is lag, but replaces it with the result once it arrives."
}
},
echo_color: {
cat: "styling",
type: ["color", "noquotes"],
desc: "A custom color for the local echo - your commands as they appear in the output window (if they are visible). Color names or hex codes may be used.",
def: "",
onChange: function(old) {
var x = prefs.echo_color.replace(/['"]+/g,'');
if (x) {
x = "#output .inputecho {color:" + x+";}";
cssMods.echo_color = setStyle(x, cssMods.echo_color);
}
}
},
background_color: {
cat: "styling",
type: ["color", "noquotes"],
desc: "A custom background color. Color names or hex codes may be used. Set 'none' to clear.",
def: "",
onChange: function(old) {
var x = prefs.background_color.replace(/['"]+/g, '');
if (x) {
x = "#output { background-color:" + x + " !important;}"
cssMods.background_color = setStyle(x, cssMods.background_color);
}
}
},
theme: {
cat: "styling",
type: ["options"],
desc: "The colors and styles used for text.",
def: "skotos",
opt: {
light: "A light background wtih dark text. The standard Skotos appearance.",
dark: "A dark background with light text. Considered by many to be easier on the eyes.",
dark_hc: "A high-contrast variant of the dark theme.",
terminal: "Old style - everything in small, monospace fonts with a dark background. Doesn't work well with most font_face settings.",
skotos: "Assume the server will set the theme"
},
onChange: function(old) { setActiveStyleSheet(prefs.theme); }
},
font_face: {
cat: "styling",
type: ["string", "noquotes"],
desc: "The custom font of the main text area. Can be any font installed on your system and available to your browser, but must be spelled correctly and the exact name it is installed as.",
def: "",
onChange: function(old) {
var x = prefs.font_face.replace(/['"]+/g,'');
if (x) x = "#core {font-family:\"" + x + "\", minionpro-regular, \"Open Sans\", Roboto, Lato, Verdana, sans-serif;}"
cssMods.font_face = setStyle(x, cssMods.font_face);
}
},
keep_last_command: {
cat: "control",
type: ["options"],
desc: "What the input area does after you send a command.",
def: "off",
opt: {
off: "After sending a command, the input area is cleared, ready for the next command.",
on: "After sending a command, that command is kept in the input area, highlighted. As a result, pressing Enter again repeats that command. If you just start typing instead, the previous command is replaced with what you type."
}
},
highlight_to_copy: {
cat: "control",
type: ["options"],
desc: "Automatically copies highlighted text in the output area to the clipboard (similar to a unix terminal). Not supported by all browsers.",
def: "off",
opt: {
off: "Highlighting text in the output window does nothing.",
on: "Highlighting text in the output window copies it to the clipboard."
},
onChange: function(old) {
if (prefs.highlight_to_copy=="on") {
addEvent(output, "mouseup", copyOutputSelection, {passive:true});
} else {
removeEvent(output, "mouseup", copyOutputSelection, {passive:true});
}
}
},
autolog: {
cat: "system",
type: ["options"],
desc: "Automatically start saving log files when the client starts.",
def: "off",
dis: true,
opt: {
off: "Do not automatically save logs.",
localstorage: "Automatically save logs in the browser's local storage. Note that the browser will automatically delete these logs at certain events (such as clearing cache/history, or when memory is needed on mobile devices), so they should be regularly backed up elsewhere.",
filesystem: "Automatically save logs to the filesystem (usually hard drive or equivalent). Requires some sort of addon/extension/plugin to enable, but when available, is less likely to run into space/deltion issues than localstorage. NOT YET ENABLED."
}
},
prompt_savelog: {
cat: "system",
type: ["options"],
desc: "Automatically prompt to save a log upon disconnect. (Does not work if the client is refreshed/closed without properly disconnecting; be sure to use EXIT or similar commands to disconnect first.)",
def: "off",
opt: {
off: "Do not automatically prompt to save logs.",
on: "Prompt to save log on disconnect"
}
},
logging_path: {
cat: "system",
type: ["string"],
desc: "For logs saved to the filesystem, this is the directory the logs are saved in. NOTE: FILESYSTEM LOGGING NOT YET ENABLED.",
def: "",
dis: true,
},
logging_format: {
cat: "system",
type: ["options"],
desc: "Format to save logs in. HTML preserves some formatting better.",
def: "html",
opt: {
html: "Save the logs as non-styled HTML, with layout preserved. These are best viewed in a browser.",
plain: "Convert logs to plaintext. These lose some layout information, but can be viewed in any text editor."
}
},
command_history_min: {
cat: "control",
type: ["integer", "nonnegative"],
desc: "The minimum length a line must be to be saved in the command history. Setting it to 2, for example, lets it ignore n, s, e, w, etc., so that more important lines are kept accessible.",
def: 1
},
text_size: {
cat: "styling",
type: ["integer", "nonnegative"],
desc: "The size (in px) of the font used for the main display. Common values are 10-24; most browsers default to 14 or 16. Note that most browsers have a built-in way to adjust the size of the entire client, usually with key combinations like Ctrl++, Ctrl+- and Ctrl+0.",
def: 0,
on0: "Your browser's default",
onChange: function(old) {var x = ((prefs.text_size > 7 && prefs.text_size < 501)?"#core {font-size:"+prefs.text_size+"px;}":""); cssMods.text_size = setStyle(x,cssMods.text_size);}
},
input_minheight: {
cat: "layout",
type: ["integer", "nonnegative"],
desc: "The default size (in lines) of the area used for input. Will automatically cap at half the client height.",
def: Math.max(2, 1 + Math.ceil((window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight) / (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth))),
onChange: function(old) {recalcInputLineHeight(true);}
},
hotkeys_enabled: {
cat: "control",
type: ["options"],
desc: "Whether to have hotkeys (keys that immediately do something when pressed) enabled. These are used primarily for numpad navigation without needing to press Enter.",
def: "off",
opt: {
off: "No hotkeys are enabled.",
when_blank: "Hotkeys are only enabled when there's nothing typed in the input window.",
always_on: "Hotkeys are enabled at all times."
}
},
hide_sidebar: {
cat: "layout",
type: ["options"],
desc: "Whether to hide one or both of the sidebars.",
def: "none",
opt: {
none: "Show both sidebars.",
auto: "Automatically hide the left sidebar if the client is very narrow. Not yet implemented.",
left: "Hide the left sidebar.",
right: "Hide the right sidebar.",
both: "Hide both sidebars."
},
onChange: function(old) {
var x = "";
var y = "";
if (prefs.hide_sidebar=="both") {
x = "#left, #right {display:none;}";
y = "#core {max-width: 100%;}";
} else if (prefs.hide_sidebar=="left"||prefs.hide_sidebar=="right") {
x = "#"+prefs.hide_sidebar+" {display:none;}";
y = "#core {max-width: calc(100% - "+document.getElementById("right").offsetWidth+"px)}";
}
cssMods.hide_sidebar_bar = setStyle(x,cssMods.hide_sidebar_bar);
cssMods.hide_sidebar_core = setStyle(y,cssMods.hide_sidebar_core);
}
}
};
//pref_options.sort(function(a, b) {
// return a.cat > b.cat;
//});
function changePrefUI(pref) {
//Todo: Track temporary changes for undo/save.
setPref(pref, document.getElementById(pref).value, true);
}
function setPref(pref, val, ignore_same) {
pref = pref.toLowerCase();
if (typeof val == "string") {
val = val.toLowerCase();
}
var info = pref_options[pref];
if (!info) {
return printUnscreened("There is no client preference named '" + safe_tags_replace(pref) +"'.", "client usererror");
}
var old = prefs[pref];
if (old==val) {
if (!ignore_same) {
printUnscreened("The client preference '" + pref + "' is already set to '" + safe_tags_replace(val) + "'.", "client");
}
return;
}
switch (info.type[0]) {
case "integer":
val = parseInt(val, 10);
if ((info.type.indexOf("nonnegative") > -1 && val < 0) || (info.type.indexOf("positive") > -1 && val < 1)) {
return printUnscreened("The value " + safe_tags_replace(val) + " is too low for " + pref +".", "client usererror");
}
if ((info.type.indexOf("nonzero") > -1 && val == 0)) {
return printUnscreened("The value for " + pref +" cannot be zero.", "client usererror");
}
break;
case "options":
if (!info.opt[val]) {
return printUnscreened("The value " + safe_tags_replace(val) + " is not a valid option for " + pref +".", "client usererror");
}
break;
case "string":
if(info.type.indexOf("noquotes") > -1) {
val = val.replace(/['"]+/g,'');
}
break;
case "color":
val = val.replace(/['"]+/g,'');
break;
default:
return printUnscreened("Client error for preference " + pref + ".", "client error");
}
prefs[pref] = val;
if (info.onChange) {
info.onChange(old);
}
printUnscreened("Client Preference '" + pref + "' changed to '" + safe_tags_replace(val) + "'.", "client");
}
function openSettings() {
showPrefs();
}
function saveSettings(clientOnly) {
}
function createSettingsInterface() {
var preference_names = Object.keys(pref_options);
var cats = [];
var name, cat, ih, classes, current_value, valid_values, val, info;
var cache = {};
//addComponent(newID, parentID, newClass, clickFunction, clickArgs, newContents, title)
addComponent("settings-ui", "body");
addComponent("settings-tabtitles", "settings-ui");
addComponent("settings-tabs", "settings-ui");
addComponent("settings-footer", "settings-ui");
addComponent("settings-savelocal", "settings-footer", false, saveSettings, [true], "<button>Client-Only Save</button>");
addComponent("settings-save", "settings-footer", false, saveSettings, [false], "<button>Save Settings</button>");
for (var i=0;i<preference_names.length;i++) {
name = preference_names[i];
info = pref_options[name];
current_value = prefs[name];
cat = info.cat;
if (cats.indexOf(cat) === -1) {
cats.push(cat);
addComponent("settingstabtitle-"+cat, "settings-tabtitles", "tabtitle", showTab, [cat], cat);
addComponent("settingstab-"+cat, "settings-tabs", "tabbody");
cache[cat] = "<table><caption>" + cat + " Preferences</caption><th>Preference</th><th>Value</th><th>Description</th>";
}
ih = "<tr><td><label for=\"setting-"+name+"\">"+name+"</label><td>";
switch (info.type[0]) {
case "options":
ih += "<select id=\"setting-"+name+"\">";
valid_values = Object.keys(info.opt);
for (var j=0;j<valid_values.length;j++) {
val = valid_values[j];
ih += "<option title=\"" + safe_tags_replace(info.opt[valid_values[j]]) + "\"" + (val===info.def?" class=\"client-defaultopt\"":"") + (val===current_value?" selected":"") + ">" + safe_tags_replace(val) + "</option>";
}
break;
case "color":
//Todo: Abstract out the creation of span tags that identify current and default values, so the code's not being repeated so much.
ih += "<input id=\"setting-"+name+"\" type=\"color\" defaultvalue=\""+info.def+"\" value=\""+current_value+"\">";
break;
case "integer":
default:
ih += "<input id=\"setting-"+name+"\" type=\"text`\" defaultvalue=\""+info.def+"\" value=\""+current_value+"\">";
}
ih += "</td><td>"+safe_tags_replace(info.desc)+"</td></tr>";
cache[cat] += ih;
}
console.log(cats);
for (cat in cats) {
cat = cats[cat];
console.log("About to fetch: settingstab-"+cat);
console.log(document.getElementById("settingstab-"+cat));
document.getElementById("settingstab-"+cat).innerHTML = cache[cat];
console.log("Done with: settingstab-"+cat);
}
console.log("D");
}
function showTab(tab) {
alert(tab);
var t, title, contents;
if (typeof(this) === "object" && this && this.className) {
title = this;
tab = this.id.substring(17);
} else {
title = document.getElementById("settingstabtitle-"+tab);
}
contents = document.getElementById("settingstab-"+tab);
if (title.className.indexOf("activetabtitle") >= 0) return;
for (t in document.getElementById("settings-tabtitles").children) {
removeClass(t, "activetabtitle");
}
for (t in document.getElementById("settings-tabs").children) {
removeClass(t, "activetab");
}
addClass(title, "activetabtitle");
addClass(contents, "activetab");
}
function showPrefs() {
//var table = ["Client Preferences:"];
var table = ["<hr>"];
var name;
var current_value;
var row;
var info;
var valid_values;
var items;
var classes;
var preference_names = Object.keys(pref_options);
var cat;
var sortorder = {};
for (var i=0;i<preference_names.length;i++){
name = preference_names[i];
console.log(name);
cat = pref_options[name].cat;
console.log(cat);
items = sortorder[cat] || [];
console.log(items);
items.push(name);
sortorder[cat] = items;
console.log(sortorder);
}
console.log(sortorder);
var preference_groups = Object.keys(sortorder);
for (var q=0;q<preference_groups.length;q++) {
cat = preference_groups[q];
console.log(cat);
preference_names = sortorder[cat];
console.log(preference_names);
table.push("<table>", "<caption>Client Preferences - " + cat.toUpperCase() + "</caption>", "<th>Preference</th><th>Settings</th><th>Description</th>");
for (var i=0;i<preference_names.length;i++){
name = preference_names[i];
current_value = prefs[name];
info = pref_options[name];
if (info.dis) continue;
row = "<tr><td class=\"client-optname\">" + safe_tags_replace(name) + "</td><td>";
switch (info.type[0]) {
case "options":
valid_values = Object.keys(info.opt);
items = [];
for (var j=0;j<valid_values.length;j++) {
classes = ((valid_values[j]==current_value?"client-currentopt":"") + (valid_values[j]==info.def?" client-defaultopt":"")).trim();
items.push("<span title=\"" + safe_tags_replace(info.opt[valid_values[j]]) + "\"" + (classes?"class=\"" + classes + "\"":"") + ">" + safe_tags_replace(valid_values[j]) + "</span>");
}
row += items.join(" | ");
break;
case "color":
//Todo: Abstract out the creation of span tags that identify current and default values, so the code's not being repeated so much.
if (current_value == info.def) {
row += "<span class=\"client-currentopt client-defaultopt\">" + safe_tags_replace(String(current_value)) + "<span style=\"background-color:" + safe_tags_replace(String(current_value)) + "\"> </span></span>";
} else {
row += "<span class=\"client-currentopt\">" + safe_tags_replace(String(current_value)) + "<span style=\"background-color:" + safe_tags_replace(String(current_value)) + "\"> </span></span> (<span class=\"client-defaultopt\">" + safe_tags_replace(String(info.def)) + "<span style=\"background-color:" + safe_tags_replace(String(info.def)) + "\"> </span>)</span>)";
}
break;
case "integer":
default:
if (current_value == info.def) {
row += "<span class=\"client-currentopt client-defaultopt\">" + safe_tags_replace(String(current_value)) + (current_value==0&&info.on0?" ["+info.on0+"]":"") + "</span>";
} else {
row += "<span class=\"client-currentopt\">" + safe_tags_replace(String(current_value)) + (current_value==0&&info.on0?" ["+info.on0+"]":"") + "</span>" + " (<span class=\"client-defaultopt\">" + safe_tags_replace(String(info.def)) + (info.def==0&&info.on0?" ["+info.on0+"]":"")+ "</span>)";
}
}
row += "</td><td>" + info.desc + (info.on0?" [0 = "+info.on0+"]":"") + "</td></tr>"
table.push(row);
}
table.push("</table>");
}
table.push("<div></div>");
table.push("<div>Hover over an option for more details. [<span class=\"client-currentopt\">current setting</span>] [<span class=\"client-defaultopt\">default setting</span>]</div>");
table.push("<div>To change a setting, use: <strong>clientpref <preferencename> <value></strong>. To save settings for next time you open the client, use <strong>clientpref save</strong>.</div><hr>");
table = table.join("");
printScreened(table, "client-info");
}
var hotkey_mapping = {
97: "go southwest",
98: "go south",
99: "go southeast",
100:"go west",
101:"look",
102:"go east",
103:"go northwest",
104:"go north",
105:"go northeast",
106:"examine here",
107:"go down",
109:"go up",
110:"exits",
111:"inventory"
}
function savePrefs() {
var toSave = {};
for (var p in prefs) {
if (prefs[p] != pref_options[p].def) {
toSave[p] = prefs[p];
}
}
toSave = JSON.stringify(toSave);
if (localStorage && localStorage.setItem) {
printUnscreened("Attempting to save preferences in local storage...", "client");
localStorage.setItem("prefs", toSave);
if (localStorage.getItem("prefs") != toSave) {
printScreened("Saving preferences to local storage failed.", "client error");
} else {
printScreened("Preferences appear to have been successfully saved.", "client");
}
} else {
printUnscreened("Local storage not found, not saving preferences in local storage.", "client");
}
}
function saveMacros() {
var toSave = JSON.stringify(macros);
if(localStorage && localStorage.setItem) {
printUnscreened("Attempting to save macros in local storage...", "client");
localStorage.setItem("macros", toSave);
if (localStorage.getItem("macros") != toSave) {
printScreened("Saving macros to local storage failed.", "client error");
} else {
printScreened("Macros appear to have been successfully saved.", "client");
}
} else {
printUnscreened("Local storage not found, not saving macros in local storage.", "client");
}
}
// Based on http://code.is-here.com/zealotry/trunk/content/macro.js, function applyMacros
function macroSubstitute(remainingInput) {
var expansions = 0;
var argsToDo = 0;
var done = "";
var arr;
var argCount = 0;
// fetch the next word
while (arr = (/([a-zA-Z0-9_]+)/).exec(remainingInput)) {
// any bits to the left of that word are added verbatim
done += RegExp.leftContext;
remainingInput = RegExp.rightContext;
var word = arr[0];
var macroMatch = macros[word];
if (macroMatch) {
// it's a macro; prepend it to the string we're working on
var outStr = macroMatch.outStr;
// then do macro-arg replacement (if any) on coming words
argsToDo = macroMatch.args;
argCount = 1;
while (argsToDo > 0) {
if (arr = (/([a-zA-Z0-9_]+)/).exec(remainingInput)) {
// leftContext is discarded here as garbage
remainingInput = RegExp.rightContext;
word = arr[0];
// make sure we're not inserting recursive junk
if (word.indexOf("%") == -1) {
// then substitute e.g. %1 for the new word
while ((index = outStr.indexOf("%" + argCount)) != -1) {
outStr = outStr.substring(0, index) + word +
outStr.substring(index + 2);
}
}
}
argCount ++;
argsToDo --;
}
// allow recursion: prepend 'input' rather than append 'done'
remainingInput = outStr + remainingInput;
expansions ++;
if (expansions > 20) {
printUnscreened("Too many macro expansions: aborting!", "client usererror");
return null;
}
} else {
// not a macro; accept the original word verbatim
done += word;
}
}
return done + remainingInput;
}
function initPrefs() {
prefs = {};
macros = {};
for (var p in pref_options) {
prefs[p] = pref_options[p].def;
}
if (localStorage && localStorage.getItem) {
loadPrefString(localStorage.getItem("prefs"));
loadMacroString(localStorage.getItem("macros"));
}
setActiveStyleSheet(prefs.theme);
}
function loadPrefString(p) {
p = JSON.parse(p);
for (var pref in p) {
setPref(pref, p[pref], true);
}
}
function loadMacroString(m) {
m = JSON.parse(m);
macros = {};
for (var macro in m) {
macros[macro] = m[macro];
}
}
// Based on http://code.is-here.com/zealotry/trunk/content/macro.js
function addMacro(inStr, outStr) {
console.log("Setting macro " + inStr + " to " + outStr);
var newMacro = new Object();
newMacro = new Object();
newMacro.inStr = inStr;
newMacro.outStr = outStr;
newMacro.args = 0;
var index;
while ((index = outStr.indexOf("%", index)) != -1) {
index++;
if (outStr[index] >= '1' && outStr[index] <= '9') {
var argIndex = outStr[index] - '0';
if (argIndex > newMacro.args) {
newMacro.args = argIndex;
}
}
}
macros[inStr] = newMacro;
}
function init() {
removeEvent(window, 'load', init, {once:true});
output = document.getElementById("output");
input = document.getElementById("commandinput");
addEvent(input, "keydown", keyDown);
addEvent(input, "mouseup", keyUp, {passive:true});
addEvent(input, "keyup", keyUp, {passive:true});
addEvent(input, "focus", restorePos, {passive:true});
addEvent(window, "mouseup", fixFocus, {passive:true});
addEvent(window, "resize", keepScrollPos, {passive:true});
addEvent(output, "mouseup", checkOutputClick);
addEvent(output, "scroll", noteScrollPos, {passive:true});
addEvent(output, "paste", redirectPaste, {passive:true});
initPrefs();
initTheatre();
recalcInputLineHeight();
debugMsg("Client initialized and ready for connection.");
initConnection();
window.focus();
c.raw = window.location == "http://test.skotos.net/orchil/marrach/marrach.htm";
}
//-----General UI
function addComponent(newID, parentID, newClass, clickFunction, clickArgs, newContents, newTitle) {
var parent = (typeof parentID == "object" ? parentID : document.getElementById(parentID));
if (!parent) reportClientError("Cannot find parent " + parentID);
var newComponent = document.createElement('div');
parent.appendChild(newComponent);
if (newID) newComponent.id = newID;
if (newClass) newComponent.className = newClass;
if (newContents) newComponent.innerHTML = newContents;
if (newTitle) newComponent.title = newTitle;
if (clickFunction) {
var fun;
if (typeof(clickFunction) == "string") {
var def = clickFunction+'("'+clickArgs.join('","')+'")';
fun = new Function(def);
//writeToConsole("Writing clickFunction " + def);
} else {
fun = clickFunction;
//writeToConsole("Writing clickFunction " + fun);
newComponent.dataset.clickargs = clickArgs;
}
addEvent(newComponent, "click", fun, {passive:true});
newComponent.style.cursor = "pointer";
}
return newComponent;
}
function connConnected() {
conn.connected = true;
printScreened("CONNECTED", "connection");
input.contentEditable = true;
input.className = input.className.replace(/\bdisabled\b/,'');
input.placeholder = "Enter a command...";
//input.removeAttribute("disabled");
input.disabled = false;
setInputValue("");
fixFocus();
if (!(c.raw)) sendSys("SKOTOS Orchil 0.2.3");
}
function connDisconnected() {
conn.connected = false;
input.contentEditable = false;
input.className += ' disabled';
input.disabled = true;
printScreened("DISCONNECTED", "connection");
input.placeholder = "";
conn = null;
if (prefs.prompt_savelog=="on" && loginDone) {
saveCurrentWindow();
}
}
function fixFocusIfUnselected(e) {
if (prefs.output_click == "focus_output" ||
(typeof window.getSelection != "undefined" && window.getSelection().toString()) ||
(typeof document.selection != "undefined" && document.selection.type == "Text" && document.selection.createRange().text)) {
cancelEvent(e);
}
}
function checkOutputClick(e) {
if (isLeftClick(e)) {
//Todo: Test/debug this.
//cancelEvent(e);
fixFocusIfUnselected(e);
} else {