-
Notifications
You must be signed in to change notification settings - Fork 46
/
monks-tokenbar.js
1883 lines (1653 loc) · 81.9 KB
/
monks-tokenbar.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
import { registerSettings, divideXpOptions } from "./settings.js";
import { TokenBar } from "./apps/tokenbar.js";
import { AssignXP, AssignXPApp } from "./apps/assignxp.js";
import { SavingThrow, SavingThrowApp } from "./apps/savingthrow.js";
import { ContestedRoll, ContestedRollApp } from "./apps/contestedroll.js";
import { LootablesApp } from "./apps/lootables.js";
import { MonksTokenBarAPI } from "./monks-tokenbar-api.js";
import { dcconfiginit } from "./plugins/dcconfig.plugin.js"
import { BaseRolls } from "./systems/base-rolls.js";
import { DS4Rolls } from "./systems/ds4-rolls.js";
import { DnD5eRolls } from "./systems/dnd5e-rolls.js";
import { DnD4eRolls } from "./systems/dnd4e-rolls.js";
import { D35eRolls } from "./systems/d35e-rolls.js";
import { PF1Rolls } from "./systems/pf1-rolls.js";
import { PF2eRolls } from "./systems/pf2e-rolls.js";
import { Tormenta20Rolls } from "./systems/tormenta20-rolls.js";
import { OSERolls } from "./systems/ose-rolls.js";
import { SFRPGRolls } from "./systems/sfrpg-rolls.js";
import { SwadeRolls } from "./systems/swade-rolls.js";
import { SW5eRolls } from "./systems/sw5e-rolls.js";
import { CoC7Rolls } from "./systems/coc7-rolls.js";
import { T2K4ERolls } from "./systems/t2k4e-rolls.js";
export let debug = (...args) => {
if (MonksTokenBar.debugEnabled > 1) console.log("DEBUG: monks-tokenbar | ", ...args);
};
export let log = (...args) => console.log("monks-tokenbar | ", ...args);
export let warn = (...args) => {
if (MonksTokenBar.debugEnabled > 0) console.warn("monks-tokenbar | ", ...args);
};
export let error = (...args) => console.error("monks-tokenbar | ", ...args);
export let i18n = key => {
return game.i18n.localize(key);
};
export let setting = key => {
return game.settings.get("monks-tokenbar", key);
};
export let patchFunc = (prop, func, type = "WRAPPER") => {
let nonLibWrapper = () => {
const oldFunc = eval(prop);
eval(`${prop} = function (event) {
return func.call(this, ${type != "OVERRIDE" ? "oldFunc.bind(this)," : ""} ...arguments);
}`);
}
if (game.modules.get("lib-wrapper")?.active) {
try {
libWrapper.register("monks-enhanced-journal", prop, func, type);
} catch (e) {
nonLibWrapper();
}
} else {
nonLibWrapper();
}
}
export const MTB_MOVEMENT_TYPE = {
FREE: 'free',
NONE: 'none',
COMBAT: 'combat'
}
/*
export let manageTokenControl = (token, isShiftPressed) => {
if (!token) return;
const options = { releaseOthers: !isShiftPressed };
const testControl = token._controlled && isShiftPressed;
testControl ? token.release(options) : token.control(options);
}*/
export class MonksTokenBar {
static tracker = false;
static tokenbar = null;
static debugEnabled = 0;
static slugify(str) {
if (str == undefined)
return "";
str = str.replace(/^\s+|\s+$/g, '');
// Make the string lowercase
str = str.toLowerCase();
const characterMap = {
'Á': 'A', 'Ä': 'A', 'Â': 'A', 'À': 'A', 'Ã': 'A', 'Å': 'A', 'Č': 'C', 'Ç': 'C',
'Ć': 'C', 'Ď': 'D', 'É': 'E', 'Ě': 'E', 'Ë': 'E', 'È': 'E', 'Ê': 'E', 'Ẽ': 'E',
'Ĕ': 'E', 'Ȇ': 'E', 'Í': 'I', 'Ì': 'I', 'Î': 'I', 'Ï': 'I', 'Ň': 'N', 'Ñ': 'N',
'Ó': 'O', 'Ö': 'O', 'Ò': 'O', 'Ô': 'O', 'Õ': 'O', 'Ø': 'O', 'Ř': 'R', 'Ŕ': 'R',
'Š': 'S', 'Ť': 'T', 'Ú': 'U', 'Ů': 'U', 'Ü': 'U', 'Ù': 'U', 'Û': 'U', 'Ý': 'Y',
'Ÿ': 'Y', 'Ž': 'Z', 'á': 'a', 'ä': 'a', 'â': 'a', 'à': 'a', 'ã': 'a', 'å': 'a',
'č': 'c', 'ç': 'c', 'ć': 'c', 'ď': 'd', 'é': 'e', 'ě': 'e', 'ë': 'e', 'è': 'e',
'ê': 'e', 'ẽ': 'e', 'ĕ': 'e', 'ȇ': 'e', 'í': 'i', 'ì': 'i', 'î': 'i', 'ï': 'i',
'ň': 'n', 'ñ': 'n', 'ó': 'o', 'ö': 'o', 'ò': 'o', 'ô': 'o', 'õ': 'o', 'ø': 'o',
'ð': 'o', 'ř': 'r', 'ŕ': 'r', 'š': 's', 'ť': 't', 'ú': 'u', 'ů': 'u', 'ü': 'u',
'ù': 'u', 'û': 'u', 'ý': 'y', 'ÿ': 'y', 'ž': 'z', 'þ': 'b', 'Þ': 'B', 'Đ': 'D',
'đ': 'd', 'ß': 'B', 'Æ': 'A', 'a': 'a', '·': '-', '/': '-', '_': '-', ',': '-'
};
const pattern = new RegExp(`[${Object.keys(characterMap).join('')}]`, 'g');
str = str.replace(pattern, match => characterMap[match]);
// Remove invalid chars
str = str.replace(/[^a-z0-9 -]/g, '')
// Collapse whitespace and replace by -
.replace(/\s+/g, '-')
// Collapse dashes
.replace(/-+/g, '-');
return str;
}
static init() {
log("initializing");
// element statics
try {
Object.defineProperty(User.prototype, "isTheGM", {
get: function isTheGM() {
return this == (game.users.find(u => u.hasRole("GAMEMASTER") && u.active) || game.users.find(u => u.hasRole("ASSISTANT") && u.active));
}
});
} catch { }
MonksTokenBar.SOCKET = "module.monks-tokenbar";
CONFIG.TextEditor.enrichers.push({ id: 'MonksTokenBarRequest', pattern: /@(Request|Contested)\[([^\]]+)\](?:{([^}]+)})?/gi, enricher: MonksTokenBar._createRequestRoll });
game.keybindings.register('monks-tokenbar', 'request-roll', {
name: 'MonksTokenBar.RequestRoll',
editable: [{ key: 'KeyR', modifiers: [KeyboardManager.MODIFIER_KEYS?.ALT] }],
restricted: true,
onDown: (data) => {
let roll = game.user.getFlag("monks-tokenbar", "lastmodeST");
if (roll == "selfroll") roll = "blindroll";
new SavingThrowApp(null, { rollmode: roll }).render(true);
},
});
game.keybindings.register('monks-tokenbar', 'request-roll-gm', {
name: 'MonksTokenBar.RequestRollGM',
editable: [{ key: 'KeyR', modifiers: [KeyboardManager.MODIFIER_KEYS?.ALT, KeyboardManager.MODIFIER_KEYS?.SHIFT] }],
restricted: true,
onDown: (data) => {
new SavingThrowApp(null, {rollmode: "selfroll"}).render(true);
},
});
registerSettings();
Handlebars.registerHelper({ selectGroups: MonksTokenBar.selectGroups });
/*
if (setting('stats') == undefined) {
//check and see if the user has selected something other than the default
if (setting('stat1-icon') != undefined || setting('stat1-resource') != undefined || setting('stat2-icon') != undefined || setting('stat2-resource') != undefined) {
let oldstats = {};
if (setting('stat1-resource') != undefined)
oldstats[setting('stat1-resource')] = setting('stat1-icon');
if (setting('stat2-resource') != undefined)
oldstats[setting('stat2-resource')] = setting('stat2-icon');
game.settings.set('monks-tokenbar', 'stats', oldstats);
}
}*/
patchFunc("Token.prototype._canDrag", function (wrapped, ...args) {
let result = wrapped(...args);
return (MonksTokenBar.allowMovement(this.document, false) ? result : false);
});
patchFunc("ChatLog.prototype._getEntryContextOptions", function (wrapped, ...args) {
let menu = wrapped.call(...args);
let canHeroPointReroll = ($li) => {
const message = game.messages.get($li[0].dataset.messageId, { strict: !0 });
if (!message.getFlag("monks-tokenbar", "what"))
return false;
let msgToken = message.getFlag("monks-tokenbar", `token${MonksTokenBar.contextId}`);
if (!msgToken)
return false;
let token = fromUuidSync(msgToken.uuid);
let actor = token?.actor ? token.actor : token;
return game.system.id == "pf2e" && !!msgToken.roll && actor.type == "character" && actor.heroPoints.value > 0 && (game.user.isGM || actor.isOwner);
//return game.user.isGM && !!message.flags.pf2e.context
//message.isRerollable && !!actor?.isOfType("character") && actor.heroPoints.value > 0
};
let canReroll = ($li) => {
const message = game.messages.get($li[0].dataset.messageId, { strict: !0 });
if (!MonksTokenBar.system.canReroll)
return false;
if (!message.getFlag("monks-tokenbar", "what"))
return false;
let msgToken = message.getFlag("monks-tokenbar", `token${MonksTokenBar.contextId}`);
if (!msgToken)
return false;
let token = fromUuidSync(msgToken.uuid);
let actor = token?.actor ? token.actor : token;
return !!msgToken.roll && actor?.type == "character" && (game.user.isGM || actor.isOwner);
};
return [...menu, ...[
{
name: "PF2E.RerollMenu.HeroPoint",
icon: '<i class="fas fa-hospital-symbol"></i>',
condition: canHeroPointReroll,
callback: $li => {
const message = game.messages.get($li[0].dataset.messageId, { strict: !0 });
let what = message.getFlag("monks-tokenbar", "what");
if (what == "savingthrow")
SavingThrow.rerollFromMessage(message, MonksTokenBar.contextId, { heroPoint: !0 });
else if (what == "contestedroll")
ContestedRoll.rerollFromMessage(message, MonksTokenBar.contextId, { heroPoint: !0 });
}
},
{
name: "Reroll and keep the new result",
icon: '<i class="fas fa-dice"></i>',
condition: canReroll,
callback: $li => {
const message = game.messages.get($li[0].dataset.messageId, { strict: !0 });
let what = message.getFlag("monks-tokenbar", "what");
if (what == "savingthrow")
SavingThrow.rerollFromMessage(message, MonksTokenBar.contextId);
else if (what == "contestedroll")
ContestedRoll.rerollFromMessage(message, MonksTokenBar.contextId);
}
},
{
name: "Reroll and keep the worst result",
icon: '<i class="fas fa-dice-one"></i>',
condition: canReroll,
callback: $li => {
const message = game.messages.get($li[0].dataset.messageId, { strict: !0 });
let what = message.getFlag("monks-tokenbar", "what");
if (what == "savingthrow")
SavingThrow.rerollFromMessage(message, MonksTokenBar.contextId, { keep: "worst" });
else if (what == "contestedroll")
ContestedRoll.rerollFromMessage(message, MonksTokenBar.contextId, { keep: "worst" });
}
},
{
name: "Reroll and keep the better result",
icon: '<i class="fas fa-dice-six"></i>',
condition: canReroll,
callback: $li => {
const message = game.messages.get($li[0].dataset.messageId, { strict: !0 });
let what = message.getFlag("monks-tokenbar", "what");
if (what == "savingthrow")
SavingThrow.rerollFromMessage(message, MonksTokenBar.contextId, { keep: "best" });
else if (what == "contestedroll")
ContestedRoll.rerollFromMessage(message, MonksTokenBar.contextId, { keep: "best" });
}
}
]];
});
/*
patchFunc("Scene.prototype.view", async function (wrapped, ...args) {
if (MonksTokenBar.tokenbar) {
MonksTokenBar.tokenbar.entries = [];
MonksTokenBar.tokenbar.refresh();
}
return await wrapped.call(this, ...args);
});
*/
}
static selectGroups(choices, options) {
const localize = options.hash['localize'] ?? false;
let selected = options.hash['selected'] ?? null;
let blank = options.hash['blank'] || null;
selected = selected instanceof Array ? selected.map(String) : [String(selected)];
// Create an option
const option = (groupid, id, label) => {
if (localize) label = game.i18n.has(label) ? game.i18n.localize(label) : label;
let key = (groupid ? groupid + ":" : "") + id;
let isSelected = selected.includes(key);
html += `<option value="${key}" ${isSelected ? "selected" : ""}>${label}</option>`
};
// Create the options
let html = "";
if (blank) option("", blank);
if (choices instanceof Array) {
for (let group of choices) {
let label = (localize ? game.i18n.localize(group.text) : group.text);
html += `<optgroup label="${label}">`;
Object.entries(group.groups).forEach(e => option(group.id, ...e));
html += `</optgroup>`;
}
} else {
if (game.system.id == "burningwheel") {
const a = RegExp.escape(Handlebars.escapeExpression(choices))
, s = new RegExp(` value=["']${a}["']`);
return options.fn(this).replace(s, "$& selected")
} else
Object.entries(choices).forEach(e => option(...e));
}
return new Handlebars.SafeString(html);
}
static getTokenEntries(tokens) {
if (typeof tokens == 'string')
tokens = tokens.split(',').map(function (item) { return item.trim(); });
let findToken = function (t) {
if (typeof t == 'string') {
t = canvas.tokens.placeables.find(p => p.name == t || p.id == t) || game.actors.find(p => p.name == t || p.id == t);
} else if (!(t instanceof Token || t instanceof Actor))
t = null;
if (t?.actor?.type == "group") {
return Array.from(t.actor.system.members);
} else if (t?.actor?.type == "party") {
return Array.from(t.actor.members);
} else
return [t];
}
tokens = (tokens || []).flatMap(t => {
if (typeof t == 'string' && t.startsWith('{') && t.endsWith('}'))
t = JSON.parse(t);
let ts = findToken(typeof t == 'object' && t.token && t.constructor.name == 'Object' ? t.token : t);
return ts.map(tkn => {
if (!tkn && !t.request) return null;
tkn = {
token: tkn,
keys: { ctrlKey: t.ctrlKey, shiftKey: t.shiftKey, altKey: t.altKey, advantage: t.advantage, disadvantage: t.disadvantage },
request: t.request,
fastForward: t.fastForward
};
Object.defineProperty(tkn, 'id', {
get: function () {
return this.token.id;
}
});
return (!!tkn.token || !!tkn.request ? tkn : null);
})
}).filter(c => !!c);
return tokens;
}
static async chatCardAction(event) {
if (!setting('capture-savingthrows'))
return;
let _getChatCardActor = async function (card) {
// Case 1 - a synthetic actor from a Token
if (card.dataset.tokenId) {
const token = await fromUuid(card.dataset.tokenId);
if (!token) return null;
return token.actor;
}
// Case 2 - use Actor ID directory
const actorId = card.dataset.actorId;
return game.actors.get(actorId) || null;
}
let _getChatCardTargets = function (card) {
let targets = canvas.tokens.controlled.filter(t => !!t.actor);
if (!targets.length && game.user.character) targets = targets.concat(game.user.character.getActiveTokens());
if (!targets.length) ui.notifications.warn(game.i18n.localize("DND5E.ActionWarningNoToken"));
return targets;
}
// Extract card data
const button = event.currentTarget;
const card = button.closest(".chat-card");
const messageId = card.closest(".message").dataset.messageId;
const message = game.messages.get(messageId);
const action = button.dataset.action;
if (action === 'save') {
if (!(game.user.isGM || message.isAuthor)) return;
const actor = await _getChatCardActor(card);
if (!actor) return;
const storedData = message.getFlag("dnd5e", "itemData");
const item = storedData ? new this(storedData, { parent: actor }) : actor.items.get(card.dataset.itemId);
const targets = _getChatCardTargets(card);
const entries = MonksTokenBar.getTokenEntries(targets);
if (entries.length) {
let savingthrow = new SavingThrowApp(entries, { request: 'save:' + button.dataset.ability, dc: item.system.save.dc });
savingthrow.requestRoll();
event.preventDefault();
event.stopImmediatePropagation();
return;
}
}
}
static get stats() {
let stats = setting('stats');
return (stats.default ? MonksTokenBar.system.defaultStats : stats) || [];
}
static setTokenSize(size) {
size = size || setting("token-size");
var r = document.querySelector(':root');
r.style.setProperty('--tokenbar-token-size', size + "px");
}
static revealDice() {
return game.dice3d ? game.settings.get("dice-so-nice", "immediatelyDisplayChatMessages") || !game.dice3d.isEnabled() : true;
}
static ready() {
game.socket.on(MonksTokenBar.SOCKET, MonksTokenBar.onMessage);
game.settings.settings.get("monks-tokenbar.stats").default = MonksTokenBar.system.defaultStats;
tinyMCE.PluginManager.add('dcconfig', dcconfiginit);
MonksTokenBar.setTokenSize();
if ((game.user.isGM || setting("allow-player")) && !setting("disable-tokenbar")) {
MonksTokenBar.tokenbar = new TokenBar();
MonksTokenBar.tokenbar.refresh();
}
if (game.user.isGM && setting('loot-sheet') != 'none' && (game.modules.get(setting('loot-sheet'))?.active || setting("loot-sheet") == "pf2e")) {
let npcObject = (CONFIG.Actor.sheetClasses.npc || CONFIG.Actor.sheetClasses.minion);
if (npcObject != undefined) {
let npcSheetNames = Object.values(npcObject)
.map((sheetClass) => sheetClass.cls)
.map((sheet) => sheet.name);
npcSheetNames.forEach((sheetName) => {
Hooks.on("render" + sheetName, (app, html, data) => {
// only for GMs or the owner of this npc
if (app?.token?.actor?.getFlag('monks-tokenbar', 'converted') && app.element.find(".revert-lootable").length == 0) {
const link = $('<a class="revert-lootable"><i class="fas fa-backward"></i>Revert Lootable</a>');
link.on("click", () => LootablesApp.revertLootable(app));
app.element.find(".window-title").after(link);
}
});
});
}
}
}
static playSound(sound, users) {
foundry.audio.AudioHelper.play({ src: sound }, (users == 'all' ? true : false));
if (users != 'all' && (users.length > 1 || users[0] != game.user.id))
MonksTokenBar.emit('playSound', { sound: sound, users: users });
}
static emit(action, args = {}) {
args.action = action;
args.senderId = game.user.id;
game.socket.emit(MonksTokenBar.SOCKET, args, (resp) => { });
}
static async onMessage(data) {
switch (data.action) {
case 'rollability': {
if (game.user.isGM) {
let message = game.messages.get(data.msgid);
const revealDice = MonksTokenBar.revealDice();
for (let response of data.response) {
if (response.roll) {
let r = Roll.fromData(response.roll);
response.roll = r;
}
}
if (data.type == 'savingthrow')
SavingThrow.updateMessage(data.response, message, revealDice);
else if (data.type == 'contestedroll')
ContestedRoll.updateMessage(data.response, message, revealDice);
}
} break;
case 'finishroll': {
if (game.user.isGM) {
let message = game.messages.get(data.msgid);
if (data.type == 'savingthrow')
SavingThrow.finishRolling(data.response, message);
else if (data.type == 'contestedroll')
ContestedRoll.finishRolling(data.response, message);
}
} break;
case 'assignxp': {
if (game.user.isTheGM) {
let message = game.messages.get(data.msgid);
AssignXP.onAssignXP(data.actorid, message);
}
} break;
case 'assigndeathst': {
if (game.user.isTheGM) {
let message = game.messages.get(data.msgid);
SavingThrow.onAssignDeathST(data.tokenid, message);
}
} break;
case 'movementchange': {
if (data.tokenid == undefined || canvas.tokens.get(data.tokenid)?.isOwner) {
ui.notifications.warn(data.msg);
if (MonksTokenBar.tokenbar != undefined) {
MonksTokenBar.tokenbar.render(true);
}
}
} break;
case 'refreshsheet': {
if (game.user.id != data.senderId) {
let actor = canvas.tokens.get(data.tokenid)?.actor;
if (actor) {
actor._sheet = null;
}
}
} break;
case 'playSound': {
if (data.users.includes(game.user.id)) {
console.log('Playing sound', data.sound);
foundry.audio.AudioHelper.play({ src: data.sound }, false);
}
} break;
case 'renderLootable': {
let entity = fromUuid(data.entityid).then(entity => {
if (game.modules.get('monks-enhanced-journal')?.active && setting('loot-sheet') == 'monks-enhanced-journal') {
if (!game.MonksEnhancedJournal.openJournalEntry(entity))
entity.sheet.render(true);
} else
entity.sheet.render(true);
})
} break;
case 'closeLootable': {
$(`#lootables[data-combat-id="${data.id}"] a.close`).click();
} break;
case 'setRolls': {
if (game.user.isGM) {
let msg = game.messages.get(data.msgid);
if (msg) {
let rolls = foundry.utils.duplicate(msg.getFlag('monks-tokenbar', "rolls") || {});
rolls[data.tokenid] = data.roll;
await msg.setFlag('monks-tokenbar', "rolls", rolls);
let response = { id: data.tokenid, roll: Roll.fromData(data.roll), finish: null, reveal: true }
const revealDice = MonksTokenBar.revealDice();
await SavingThrow.updateMessage([response], msg, revealDice);
}
}
} break;
case 'updateReroll': {
if (game.user.isTheGM) {
let msg = game.messages.get(data.msgid);
if (msg) {
if (data.type == "savingthrow")
SavingThrow.updateReroll(msg, data.tokenid, Roll.fromData(data.roll), data.options);
else if(data.type == "contestedroll")
ContestedRoll.updateReroll(msg, data.tokenid, Roll.fromData(data.roll), data.options);
}
}
} break;
}
}
static manageTokenControl(tokens, options) {
let { shiftKey, force } = options;
//if !shift then release all currently selected
if (!shiftKey || force)
canvas.tokens.releaseAll();
if (!tokens) return;
tokens = (tokens instanceof Array ? tokens : [tokens]);
//select all token for control
const controlOptions = { releaseOthers: !shiftKey && !force };
tokens.forEach(token => (token._controlled && shiftKey && tokens.length == 1 ? token.release(controlOptions) : token.control(controlOptions)));
//document.getSelection().removeAllRanges();
return !shiftKey;
}
static isMovement(movement) {
return movement != undefined && MTB_MOVEMENT_TYPE[movement.toUpperCase()] != undefined;
}
static getDiceSound() {
const has3DDiceSound = game.modules.get("dice-so-nice")?.active;
return (!has3DDiceSound ? CONFIG.sounds.dice : null);
}
static async changeGlobalMovement(movement) {
if (movement == MTB_MOVEMENT_TYPE.COMBAT && (game.combat == undefined || !game.combat.started))
return;
log('Changing global movement', movement);
await game.settings.set("monks-tokenbar", "movement", movement);
//clear all the tokens individual movement settings
if (MonksTokenBar.tokenbar != undefined) {
let tokenbar = MonksTokenBar.tokenbar;
for (let i = 0; i < tokenbar.entries.length; i++) {
await tokenbar.entries[i].token?.setFlag("monks-tokenbar", "movement", null);
if (tokenbar.entries[i].token)
tokenbar.entries[i].token._movementNotified = null;
};
tokenbar.render(true);
}
MonksTokenBar.displayNotification(movement);
}
static async changeTokenMovement(movement, tokens) {
if (tokens == undefined)
return;
if (!MonksTokenBar.isMovement(movement))
return;
tokens = tokens instanceof Array ? tokens : [tokens];
log('Changing token movement', tokens);
let newMove = (game.settings.get("monks-tokenbar", "movement") != movement ? movement : null);
for (let token of tokens) {
if (token instanceof Token)
token = token.document;
let oldMove = token.getFlag("monks-tokenbar", "movement");
if (newMove != oldMove) {
await token.setFlag("monks-tokenbar", "movement", newMove);
delete token._movementNotified;
let dispMove = token.getFlag("monks-tokenbar", "movement") || game.settings.get("monks-tokenbar", "movement") || MTB_MOVEMENT_TYPE.FREE;
MonksTokenBar.displayNotification(dispMove, token);
/*if (MonksTokenBar.tokenbar != undefined) {
let tkn = MonksTokenBar.tokenbar.entries.find(t => { return t.id == token.id });
if (tkn != undefined)
tkn.movement = newMove;
} */
}
}
//if (MonksTokenBar.tokenbar != undefined)
// MonksTokenBar.tokenbar.render(true);
}
static async changeTokenPanning(tokens) {
if (tokens == undefined)
return;
tokens = tokens instanceof Array ? tokens : [tokens];
log('Changing token panning', tokens);
for (let token of tokens) {
let oldPanning = token.getFlag("monks-tokenbar", "nopanning");
await token.setFlag("monks-tokenbar", "nopanning", !oldPanning);
}
}
static displayNotification(movement, token) {
if (game.settings.get("monks-tokenbar", "notify-on-change")) {
let msg = (token != undefined ? token.name + ": " : "") + i18n("MonksTokenBar.MovementChanged") + (movement == MTB_MOVEMENT_TYPE.FREE ? i18n("MonksTokenBar.FreeMovement") : (movement == MTB_MOVEMENT_TYPE.NONE ? i18n("MonksTokenBar.NoMovement") : i18n("MonksTokenBar.CombatTurn")));
ui.notifications.warn(msg);
log('display notification');
MonksTokenBar.emit('movementchange',
{
msg: msg,
tokenid: token?.id
}
);
}
}
static allowMovement(token, notify = true) {
let blockCombat = function (token) {
//combat movement is only acceptable if the token is the current token.
//or the previous token
//let allowPrevMove = game.settings.get("combatdetails", "allow-previous-move");
let curCombat = game.combats.active;
if (setting('debug'))
log('checking on combat ', curCombat, (curCombat && curCombat.started));
if (curCombat && curCombat.started) {
let entry = curCombat.combatant;
let allowNpc = false;
if (game.settings.get("monks-tokenbar", "free-npc-combat")) {
let curPermission = entry.actor?.ownership ?? {};
let tokPermission = token.actor?.ownership ?? {};
let ownedUsers = Object.keys(curPermission).filter(k => curPermission[k] === 3);
allowNpc = ownedUsers.some(u => tokPermission[u] === 3 && !game.users?.get(u)?.isGM)
&& curCombat.turns.every(t => { return t.tokenId !== token.id; });
}
if (setting('free-vehicle-combat') && entry.actor?.type == "vehicle" && entry.actor?.isOwner)
allowNpc = true;
log('Checking movement', entry.name, token.name, entry, token.id, token, allowNpc);
return !(entry.tokenId == token.id || allowNpc || (setting("allow-after-movement") && curCombat.previous.tokenId == token.id));
}
return true;
}
if (!game.user.isGM && token != undefined) {
let movement = token.getFlag("monks-tokenbar", "movement") || game.settings.get("monks-tokenbar", "movement") || MTB_MOVEMENT_TYPE.FREE;
if (setting('debug'))
log('movement ', movement, token);
if (movement == MTB_MOVEMENT_TYPE.NONE ||
(movement == MTB_MOVEMENT_TYPE.COMBAT && blockCombat(token))) {
//prevent the token from moving
if (setting('debug'))
log('blocking movement');
if (notify && (!(token._movementNotified ?? false))) {
ui.notifications.warn(movement == MTB_MOVEMENT_TYPE.COMBAT ? i18n("MonksTokenBar.CombatTurnMovementLimited") : i18n("MonksTokenBar.NormalMovementLimited"));
token._movementNotified = true;
setTimeout(function (token) {
delete token._movementNotified;
log('unsetting notified', token);
}, 2000, token);
}
return false;
}
}
return true;
}
static async onDeleteCombat(combat) {
if (game.user.isGM) {
if (combat.started == true) {
let showXP = game.settings.get("monks-tokenbar", "show-xp-dialog") && MonksTokenBar.system.showXP;
let showLoot = setting("loot-sheet") != 'none' && (game.modules.get(setting("loot-sheet"))?.active || setting("loot-sheet") == "pf2e");
let axpa;
if (showXP) {
axpa = new AssignXPApp(combat, showLoot ? { classes: ["dual"] } : null);
await axpa.render(true);
}
/*
if (game.settings.get("monks-tokenbar", "show-xp-dialog") && (game.system.id !== "sw5e" || (game.system.id === "sw5e" && !game.settings.get('sw5e', 'disableExperienceTracking')))) {
axpa = new AssignXPApp(combat);
await axpa.render(true);
}*/
if (showLoot) {
let lapp = new LootablesApp(combat, showXP ? { classes: ["dual"] } : null);
if (!lapp.entries.length)
lapp.close();
else {
await lapp.render(true);
}
}
}
if (game.combats.combats.length == 0) {
//set movement to free movement
let movement = setting("movement-after-combat");
if (movement != 'ignore')
MonksTokenBar.changeGlobalMovement(movement);
}
}
}
static getNameList(list) {
list = list.filter(g => g.groups);
for (let attr of list) {
attr.label = attr.label ?? attr.text;
attr.groups = foundry.utils.duplicate(attr.groups);
for (let [k, v] of Object.entries(attr.groups)) {
attr.groups[k] = v?.label || v?.text || v;
}
}
return list;
}
static getRequestName(requestoptions, request, actors) {
let name = '';
switch (request.type) {
case 'ability': name = i18n("MonksTokenBar.AbilityCheck"); break;
case 'save': name = i18n("MonksTokenBar.SavingThrow"); break;
case 'dice': name = i18n("MonksTokenBar.Roll"); break;
default:
name = (request.key != 'death' && request.key != 'init' ? i18n("MonksTokenBar.Check") : "");
}
let rt = requestoptions.find(o => {
return o.id == (request.type || request.key);
});
if (!rt && actors) {
for (let actor of actors) {
let item = actor.items.find(i => i.type == request.type && (MonksTokenBar.slugify(i.name) == request.key || i.getFlag("core", "sourceId") == request.key));
if (item) {
rt = { text: item.name };
break;
}
}
}
let req = (rt?.groups && rt?.groups[request.key]) || (request.type == "dice" && request.name);
let flavor = i18n(req?.label || req || rt?.text || "MonksTokenBar.Unknown");
switch (game.i18n.lang) {
case "pt-BR":
case "es":
name = name + ": " + flavor;
break;
case "en":
default:
name = flavor + " " + name;
}
return name;
}
static findBestRequest(requests, options) {
if (requests) {
let opt = options.filter(o => o);
requests = requests instanceof Array ? requests : [requests];
for (let i = 0; i < requests.length; i++) {
let request = requests[i];
if (!request)
continue;
let type = request.type
let key = request.key
if (typeof request == "string") {
if (request.indexOf(':') > -1) {
let parts = request.split(':');
type = parts[0];
key = parts[1];
} else
key = request;
}
//correct the type if it's a string
if (type && type.toLowerCase() == "saving")
type = "save";
let optType = (type ? opt.find(o => o.id == type.toLowerCase() || i18n(o.text).toLowerCase() == type.toLowerCase()) : null);
//correct the key
optType = (optType ? [optType] : opt).find(g => {
return Object.entries(g.groups).find(([k, v]) => {
let result = i18n(v).toLowerCase() == key.toLowerCase() || k == key.toLowerCase();
if (result) key = k;
return result;
});
});
if (optType)
requests[i] = { type: optType.id, key: key, slug: `${optType.id}${optType.id ? ':' : ''}${key}` };
}
return requests;
}
return null;
}
static setGrabMessage(message, event) {
if (!MonksTokenBar.system.canGrab)
return;
if (MonksTokenBar.grabmessage != undefined) {
$('#chat-log .chat-message[data-message-id="' + MonksTokenBar.grabmessage.id + '"]').removeClass('grabbing');
}
if (MonksTokenBar.grabmessage == message)
MonksTokenBar.grabmessage = null;
else {
MonksTokenBar.grabmessage = message;
if (message != undefined)
$('#chat-log .chat-message[data-message-id="' + MonksTokenBar.grabmessage.id + '"]').addClass('grabbing');
}
if (event.stopPropagation) event.stopPropagation();
if (event.preventDefault) event.preventDefault();
event.cancelBubble = true;
event.returnValue = false;
}
static selectActors(message, filter, event) {
let tokens = Object.entries(message.flags['monks-tokenbar'])
.map(([k, v]) => { return (k.startsWith('token') ? v : null) })
.filter(filter)
.map(t => { return canvas.tokens.get(t?.id); })
.filter(t => t);
MonksTokenBar.manageTokenControl(tokens, { shiftKey: event?.originalEvent?.shiftKey, force: true });
if (event) {
if (event.stopPropagation) event.stopPropagation();
if (event.preventDefault) event.preventDefault();
event.cancelBubble = true;
event.returnValue = false;
}
}
static onClickMessage(message, html) {
if (MonksTokenBar.grabmessage != undefined) {
//make sure this message matches the grab message
if (message.rolls.length) {
let tokenId = message.speaker.token;
let msgtoken = MonksTokenBar.grabmessage.getFlag('monks-tokenbar', 'token' + tokenId);
if (msgtoken != undefined) {
if (MonksTokenBar.grabmessage.getFlag('monks-tokenbar', 'what') == 'contestedroll')
ContestedRoll.updateMessage([{ id: tokenId, roll: message.rolls[0] }], MonksTokenBar.grabmessage);
else
SavingThrow.updateMessage([{ id: tokenId, roll: message.rolls[0] }], MonksTokenBar.grabmessage);
if (setting('delete-after-grab'))
message.delete();
MonksTokenBar.grabmessage = null;
}
}
}
}
static toggleMovement(combatant, event) {
event.preventDefault();
event.stopPropagation();
let movement = (combatant.token.getFlag('monks-tokenbar', 'movement') == MTB_MOVEMENT_TYPE.FREE ? MTB_MOVEMENT_TYPE.COMBAT : MTB_MOVEMENT_TYPE.FREE);
this.changeTokenMovement(movement, combatant.token.object);
$(event.currentTarget).toggleClass('active', movement);
}
static getLootSheetOptions(lootType) {
let lootsheetoptions = { 'none': 'Do not convert' };
if (game.modules.get("lootsheetnpc5e")?.active)
lootsheetoptions['lootsheetnpc5e'] = "Loot Sheet NPC 5e";
if (game.modules.get("merchantsheetnpc")?.active)
lootsheetoptions['merchantsheetnpc'] = "Merchant Sheet NPC";
if (game.modules.get("item-piles")?.active)
lootsheetoptions['item-piles'] = "Item Piles";
if (game.modules.get("monks-enhanced-journal")?.active && game.modules.get("monks-enhanced-journal").version > "1.0.39" && lootType !='convert')
lootsheetoptions['monks-enhanced-journal'] = "Monk's Enhanced Journal";
if (game.system.id == "pf2e")
lootsheetoptions['pf2e'] = "PF2e Party Stash";
return lootsheetoptions;
}
static refreshDirectory(data) {
ui[data.name]?.render();
}
static async lootEntryListing(ctrl, html, collection = game.journal, uuid) {
async function selectItem(event) {
event.preventDefault();
event.stopPropagation();
let id = event.currentTarget.dataset.uuid;
ctrl.val(id).change();
let name = await getEntityName(id);
$('.journal-select-text', ctrl.next()).html(name);
$('.journal-list.open').removeClass('open');
$(event.currentTarget).addClass('selected').siblings('.selected').removeClass('selected');
}
async function getEntityName(id) {
let entity = null;
try {
entity = (id ? await fromUuid(id) : null);
} catch {
entity = "";
}
if (entity instanceof JournalEntryPage || entity instanceof Actor)
return "<i>Adding</i> to <b>" + entity.name + "</b>";
else if (entity instanceof JournalEntry)
return "<i>Adding</i> new loot page to <b>" + entity.name + "</b>";
else if (entity instanceof Folder)
return (entity.documentClass.documentName == "JournalEntry" ? "<i>Creating</i> new Journal Entry within <b>" + entity.name + "</b> folder" : "<i>Creating</i> Actor within <b>" + entity.name + "</b> folder");
else if (id == "convert")
return "<i>Convert</i> tokens";
else if (id == "root") {
let lootsheet = setting('loot-sheet');
let isLootActor = ['lootsheetnpc5e', 'merchantsheetnpc', 'item-piles'].includes(lootsheet);
return `<i>Creating</i> ${isLootActor ? "Actor" : "Journal Entry"} in the <b>root</b> folder`;
} else
return "Unknown";
}
function getEntries(folderID, contents) {
let createItem = $('<li>').addClass('journal-item create-item').attr('data-uuid', folderID || "root").html($('<div>').addClass('journal-title').toggleClass('selected', uuid == undefined).html("-- create entry here --")).click(selectItem.bind())
let result = collection.preventCreate ? [] : [createItem];