Warning : session_start(): open(/var/lib/php/sessions/sess_khdv904hnhida8bjq6qe40st7j, O_RDWR) failed: No space left on device (28) in /var/www/tb-usercake/models/config.php on line 51
Warning : session_start(): Failed to read session data: files (path: /var/lib/php/sessions) in /var/www/tb-usercake/models/config.php on line 51
//FILENAME: pkg_dtb/dtb.java
package pkg_dtb;
import java.util.*;
import java.util.zip.*;
import java.util.List;
import java.util.regex.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.table.*;
import java.io.*;
import java.net.*;
import java.lang.reflect.*;
import java.lang.ref.*;
import java.lang.management.*;
import java.security.*;
import java.security.spec.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.math.*;
import net.dv8tion.jda.core.events.Event;
import net.dv8tion.jda.core.events.user.update.*;
import net.dv8tion.jda.core.events.guild.member.*;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.requests.restaction.MessageAction;
import net.dv8tion.jda.core.requests.RestAction;
import java.util.function.Consumer;
import javax.swing.border.*;
import java.awt.datatransfer.StringSelection;
import java.text.SimpleDateFormat;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import javax.swing.Timer;
import java.text.NumberFormat;
import javax.swing.undo.UndoManager;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.util.TimeZone;
import java.awt.geom.*;
import net.dv8tion.jda.core.*;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.hooks.*;
import net.dv8tion.jda.core.events.message.*;
import net.dv8tion.jda.core.events.message.react.*;
public class dtb {
abstract static public class DynTalkBot2 extends DynServerAwareDiscordBot {
static public boolean _switchableField_myName = true;
public String myName = "Anonymous bot";
transient public boolean useAGIBlueForDropPunctuation = true;
transient public boolean preprocessAtSelfToMyName = true;
transient public boolean dropPunctuation = true;
transient public boolean ngbCommands = true;
public List authorizedUsers = ll(547706854680297473L);
static public class ISaid implements IFieldsToList {
public long channelID;
public long date;
public String text;
public ISaid() {
}
public ISaid(long channelID, long date, String text) {
this.text = text;
this.date = date;
this.channelID = channelID;
}
public String toString() {
return "ISaid(" + channelID + ", " + date + ", " + text + ")";
}
public boolean equals(Object o) {
if (!(o instanceof ISaid))
return false;
ISaid x = (ISaid) o;
return eq(channelID, x.channelID) && eq(date, x.date) && eq(text, x.text);
}
public int hashCode() {
int h = 69986258;
h = boostHashCombine(h, _hashCode(channelID));
h = boostHashCombine(h, _hashCode(date));
h = boostHashCombine(h, _hashCode(text));
return h;
}
public Object[] _fieldsToList() {
return new Object[] { channelID, date, text };
}
}
public void init() {
super.init();
onPostedInChannel.add((channel, msg) -> {
if (channel instanceof Channel) {
Guild guild = ((Channel) channel).getGuild();
if (guild == null)
return;
ByServer bs = getByServer(guild);
long channelID = ((Channel) channel).getIdLong();
mapPut(bs.lastSaidInChannel, channelID, nu(ISaid.class, "channelID", channelID, "text", msg));
change();
}
});
dm_vmBus_onMessage_q("discordGuildJoin", new VF1() {
public void get(Map map) {
try {
{
if (!(map.get("module") == module()))
return;
}
print("Got join");
getByServer(getLong("guildID", map), true).onUserJoin(getLong("userID", map), map);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret unless map.get('module) == module();\r\n print(\"Got join\");\r\n get...";
}
});
onDiscordEvent(e -> {
if (e instanceof UserUpdateOnlineStatusEvent)
getByServer(((UserUpdateOnlineStatusEvent) e).getGuild()).onOnlineStatusChange(((UserUpdateOnlineStatusEvent) e));
});
}
public class ByServer extends DynServerAwareDiscordBot.ByServer {
transient public Lock lock;
public List guildAuthorizedUsers = synchroList();
public Map lastSaidInChannel = synchroMap();
public long preferredChannelInGuild;
public DynTalkBot2 m2() {
return DynTalkBot2.this;
}
public void onUserJoin(long userID, Object... __) {
}
public void onOnlineStatusChange(UserUpdateOnlineStatusEvent e) {
}
@Override
public String answer(String input, Map map) {
if (preferredChannelInGuild == 0) {
long channelID = longPar("channelID", map);
if (channelID != 0) {
preferredChannelInGuild = channelID;
change();
}
}
String answer = processLine(input, map);
{
String __2 = super.answer(input, map);
if (!empty(__2))
return __2;
}
return answer;
}
public String dropMyPrefixOrNull(String s) {
String sOld = s;
s = dropPrefixICTrim_orNull(myPrefix(), s);
if (s == null)
print("no got prefix: " + quote(myPrefix()) + " / " + quote(sOld));
return s;
}
public String processLine(String s, Object... __) {
s = preprocess(s, __);
return processSimplifiedLine(s, __);
}
public String preprocess(String s, Object... __) {
print("Preprocessing: " + s);
if (preprocessAtSelfToMyName && discordBotID != 0)
s = replace(s, atSelf(), " " + myName + " ");
if (dropPunctuation)
s = dropPunctuation3_withAGIBlue(useAGIBlueForDropPunctuation, s);
s = trim(simpleSpaces_noTok(s));
print("simplified >> " + quote(s));
return s;
}
public String myPrefix() {
return preprocessAtSelfToMyName ? (endsWithLetterOrDigit(myName) ? myName + " " : myName) : (dropPunctuation ? replace(atSelf(), "@", "") : atSelf()) + " ";
}
synchronized public Lock myLock() {
if (lock == null)
lock = lock();
return lock;
}
public String processSimplifiedLine(String input, Object... __) {
Lock __0 = myLock();
lock(__0);
try {
Matches m = new Matches();
input = dropMyPrefixOrNull(input);
if (input == null)
return null;
if (ngbCommands) {
if (eqicOneOf(input, "support channel", "support server", "support"))
return "Get support for me here: " + nextGenBotsDiscordInvite();
if (eqicOneOf(input, "source", "sources", "source code"))
return snippetLink(programID());
}
if (swic_trim(input, "add master ", m)) {
String __3 = checkAuth(__);
if (!empty(__3))
return __3;
setAdd(authorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. Have " + n2(l(authorizedUsers), "master");
}
if (eqic(input, "masters"))
return renderMasters();
if (swic_trim(input, "delete master ", m)) {
String __4 = checkAuth(__);
if (!empty(__4))
return __4;
remove(authorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. Have " + n2(l(authorizedUsers), "master");
}
if (swic_trim(input, "add guild master ", m)) {
String __5 = checkPerGuildAuth(__);
if (!empty(__5))
return __5;
setAdd(guildAuthorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. " + renderGuildMasters();
}
if (eqic(input, "guild masters"))
return renderGuildMasters();
if (swic_trim(input, "delete guild master ", m)) {
String __6 = checkPerGuildAuth(__);
if (!empty(__6))
return __6;
remove(guildAuthorizedUsers, parseFirstLong(m.rest()));
change();
return "Okidoki. " + renderGuildMasters();
}
if (eqic(input, "guild count")) {
String __7 = checkAuth(__);
if (!empty(__7))
return __7;
return renderGuildCount();
}
if (eqic(input, "guild names")) {
String __8 = checkAuth(__);
if (!empty(__8))
return __8;
return renderGuildNames();
}
return null;
} finally {
unlock(__0);
}
}
public String renderGuildMasters() {
return empty(guildAuthorizedUsers) ? "Only this guild's owner can control me." : "I am controlled by this guild's owner and these people: " + joinWithComma(map("discordAtPlusID", guildAuthorizedUsers));
}
public String renderGuildCount() {
return "Total guilds joined: " + guildCount + ". Live guilds: " + liveGuildCount();
}
public String renderGuildNames() {
return lines(map(discord.getGuilds(), g -> g.getName()));
}
public boolean authed(Object... __) {
return contains(authorizedUsers, optPar("userID", __));
}
public boolean perGuildAuthed(Object... __) {
long userID = longPar("userID", __);
return contains(guildAuthorizedUsers, userID) || guildID != 0 && userID == getGuild().getOwner().getUser().getIdLong();
}
public Guild getGuild() {
return guildID == 0 ? null : discord.getGuildById(guildID);
}
public String checkAuth(Object... __) {
long userID = longPar("userID", __);
boolean result = authed(__);
print("Auth-checking user ID: " + userID + " => " + result);
if (!result)
return "You are not authorized";
return null;
}
public String checkPerGuildAuth(Object... __) {
long userID = longPar("userID", __);
boolean result = perGuildAuthed(__);
print("Guild-auth-checking user ID: " + userID + " => " + result);
if (!result)
return "You are not authorized";
return null;
}
public String guildStructure() {
return structure_nullingInstancesOfClass(_getClass(module()), this);
}
}
public String serveGuildBackup(MessageChannel channel, Guild guild, String data) {
if (guild == null)
return "Do this in a guild";
if (containsDiscordToken(data))
return "DISCORD TOKEN EXPOSED ALARM!! NOTIFY ADMINISTRATOR";
String baseName = urlencode(jda_selfUserName(discord)) + "-" + guild.getIdLong() + "-" + ymd_minus_hms();
String zipName = baseName + ".zip";
File zip = programFile("backups/" + zipName);
createZipFileWithSingleTextFile(zip, baseName + ".txt", data);
channel.sendMessage("Here's my latest brain contents for this guild.").addFile(zip).queue();
return null;
}
public String serveGuildBackup(MessageChannel channel, Guild guild, ByServer bs) {
return serveGuildBackup(channel, guild, bs.guildStructure());
}
public String atSelfOrMyName() {
return preprocessAtSelfToMyName ? myName : atSelf();
}
public String renderMasters() {
return empty(authorizedUsers) ? "I have no masters." : "My masters are: " + joinWithComma(map("discordAtPlusID", authorizedUsers));
}
}
static abstract public class VF1 implements IVF1 {
public abstract void get(A a);
}
static public interface IFieldsToList {
public Object[] _fieldsToList();
}
static public class Matches {
public String[] m;
public Matches() {
}
public Matches(String... m) {
this.m = m;
}
public String get(int i) {
return i < m.length ? m[i] : null;
}
public String unq(int i) {
return unquote(get(i));
}
public String fsi(int i) {
return formatSnippetID(unq(i));
}
public String fsi() {
return fsi(0);
}
public String tlc(int i) {
return unq(i).toLowerCase();
}
public boolean bool(int i) {
return "true".equals(unq(i));
}
public String rest() {
return m[m.length - 1];
}
public int psi(int i) {
return Integer.parseInt(unq(i));
}
public String toString() {
return "Matches(" + joinWithComma(quoteAll(asList(m))) + ")";
}
public int hashCode() {
return _hashCode(toList(m));
}
public boolean equals(Object o) {
return o instanceof Matches && arraysEqual(m, ((Matches) o).m);
}
}
abstract static public class DynServerAwareDiscordBot extends DynDiscordHopper {
public Map dataByServer = new HashMap();
public int guildCount;
transient public IF0 makeByServer;
public class ByServer extends DynamicObject {
public long guildID;
public boolean isGuild = false;
public String answer(String s, Map map) {
return null;
}
public boolean setField(String name, Object value) {
if (set_trueIfChanged(this, name, value))
return false;
{
_change();
return true;
}
}
public Member getSelfMember(Guild guild) {
return guild.getMember(getSelfUser());
}
}
@Override
public String answer(String input, Map map) {
String __1 = super.answer(input, map);
if (!empty(__1))
return __1;
long guildID = toLong(map.get("guildID"));
long id = guildID;
print("Guild ID: " + guildID);
if (id == 0) {
id = toLong(map.get("userID"));
print("User ID: " + id);
}
A data = getByServer(id, id == guildID);
Message msg = (Message) (map.get("msg"));
if (msg != null && nempty(msg.getAttachments()))
return data.answer(input, map);
else
return lines_rtrim(nempties(map(s -> data.answer(s, map), splitIntoLines(input))));
}
public A getByServer(long id, boolean isGuild) {
return pairA(getByServer2(id, isGuild));
}
public Pair getByServer2(long id, boolean isGuild) {
A data;
boolean isNew = false;
Pair __2 = syncGetOrCreate2(dataByServer, id, makeByServer);
data = __2.a;
isNew = __2.b;
data.isGuild = isGuild;
if (isGuild && data.guildID == 0) {
data.guildID = id;
change();
}
if (isNew) {
if (data.isGuild)
++guildCount;
change();
}
return pair(data, isNew);
}
public A getByServer(Guild guild) {
return guild == null ? null : getByServer(guild.getIdLong(), true);
}
public void start() {
super.start();
if (guildCount == 0)
setField("guildCount", countValuesWhere_sync(dataByServer, "isGuild", true));
}
public int liveGuildCount() {
return l(discord.getGuilds());
}
public long idForByServer(ByServer bs) {
return bs == null ? 0 : toLong(keyForValue_sync(dataByServer, (A) bs));
}
public List splitIntoLines(String s) {
return tlft(s);
}
}
static public interface IF0 {
public A get();
}
static public ThreadLocal DynamicObject_loading = new ThreadLocal();
static public class DynamicObject {
public String className;
public LinkedHashMap fieldValues;
public DynamicObject() {
}
public DynamicObject(String className) {
this.className = className;
}
public Map _map() {
return fieldValues;
}
}
abstract static public class DynDiscordHopper extends DynPrintLogAndEnabled {
static public boolean _switchableField_discordToken = true;
public String discordToken;
public String discordBotName;
public long discordBotID;
public boolean reactToBots = true;
transient public JDA discord;
transient public Color discordImageEmbedMysteriousLineColor = colorFromHex("36393f");
transient public List> onPostedInChannel = syncList();
transient public Consumer onQueueError = error -> {
AutoCloseable __26 = enter();
try {
printStackTrace(error);
} finally {
_close(__26);
}
};
public void startDiscord() {
if (!discordEnabled()) {
print("Not enabled");
return;
}
vm_cleanPrints();
logModuleOutput();
discord = discordBot(new ListenerAdapter() {
@Override
public void onMessageUpdate(MessageUpdateEvent e) {
try {
AutoCloseable __27 = enter();
try {
{
if (!discordEnabled() || !licensed())
return;
}
Message msg = e.getMessage();
long msgID = msg.getIdLong();
User user = e.getAuthor();
long userID = user == null ? 0 : user.getIdLong();
String content = e.getMessage().getContentRaw();
MessageChannel channel = e.getChannel();
long channelID = channel.getIdLong();
String rendered = msgID + ": " + content;
print("Message edited: " + rendered);
vmBus_send("editedDiscordMessage", litmapparams("event", e, "module", dm_me(), "msgID", msgID, "msg", msg, "content", content, "channelID", channelID, "channel", channel, "user", user, "userID", userID));
Object lineConcept = dm_discord_lineForMsgID_unimported(msgID);
if (lineConcept == null)
return;
call(lineConcept, "_setField", "editedText", content);
} finally {
_close(__27);
}
} catch (Throwable __e) {
_handleException(__e);
}
}
@Override
public void onMessageReceived(MessageReceivedEvent e) {
try {
AutoCloseable __28 = enter();
try {
{
if (!discordEnabled() || !licensed())
return;
}
User user = e.getAuthor();
if (!reactToUser(user)) {
print("Not reacting to user " + user);
return;
}
boolean bot = user.isBot();
long msgID = e.getMessage().getIdLong();
long userID = user.getIdLong();
Guild guild = e.getGuild();
long guildID = toLong(call(guild, "getIdLong"));
Member member = e.getMember();
String userName = member == null ? null : member.getNickname();
if (userName == null && member != null)
userName = member.getEffectiveName();
if (userName == null)
userName = e.getAuthor().getName();
final Message msg = e.getMessage();
MessageChannel channel = e.getChannel();
long channelID = channel.getIdLong();
boolean isPrivate = e.getChannelType() == ChannelType.PRIVATE;
String content = trim(msg.getContentRaw());
print("Msg from " + userName + ": " + content);
vmBus_send("incomingDiscordMessage", litmapparams("fromBot", bot, "module", dm_me(), "msgID", msgID, "userID", userID, "userName", userName, "event", e, "guildID", guildID, "guild", guild, "member", member, "msg", msg, "content", content, "isPrivate", isPrivate, "channelID", channelID, "channel", channel));
} finally {
_close(__28);
}
} catch (Throwable __e) {
_handleException(__e);
}
}
@Override
public void onMessageReactionAdd(MessageReactionAddEvent e) {
try {
AutoCloseable __29 = enter();
try {
{
if (!discordEnabled() || !licensed())
return;
}
MessageReaction r = e.getReaction();
if (!reactToUser(e.getUser()))
return;
boolean bot = e.getUser().isBot();
long msgID = r.getMessageIdLong();
String emoji = r.getReactionEmote().getName();
vmBus_send("incomingDiscordReaction", litmapparams("fromBot", bot, "module", dm_me(), "msgID", msgID, "emoji", emoji));
} finally {
_close(__29);
}
} catch (Throwable __e) {
_handleException(__e);
}
}
@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
try {
AutoCloseable __30 = enter();
try {
print("Got guild join");
{
if (!discordEnabled() || !licensed())
return;
}
print("Join >> getting user ID");
long userID = rcall_long("getIdLong", rcall("getUser", event.getMember()));
print("Join >> sending");
vmBus_send("discordGuildJoin", litmapparams("module", dm_me(), "event", event, "userID", userID, "guildID", discord_guildIDFromEvent_gen(event)));
} finally {
_close(__30);
}
} catch (Throwable __e) {
_handleException(__e);
}
}
@Override
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
try {
AutoCloseable __31 = enter();
try {
print("Got guild leave");
{
if (!discordEnabled() || !licensed())
return;
}
long userID = rcall_long("getIdLong", rcall("getUser", event.getMember()));
vmBus_send("discordGuildLeave", litmapparams("module", dm_me(), "event", event, "userID", userID));
} finally {
_close(__31);
}
} catch (Throwable __e) {
_handleException(__e);
}
}
}, "token", discordToken);
dm_registerAs("liveDiscordModule");
dm_vmBus_answerToMessage("activeDiscordTokens", new F0>() {
public List get() {
try {
return ll(discordToken);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret ll(discordToken);";
}
});
try {
setField("discordBotName", jda_selfUserName(discord));
setField("discordBotID", jda_selfUserID(discord));
} catch (Throwable __e) {
_handleException(__e);
}
print("Bot name: " + discordBotName);
}
public void cleanMeUp() {
if (discord != null) {
try {
print("Shutting down discord");
discord.shutdown();
print("Bot shut down");
} catch (Throwable __e) {
_handleException(__e);
}
}
discord = null;
}
public Object userConcept(User user) {
String crud = dm_gazelle_linesCRUD();
Object userConcept = dm_call(crud, "uniqUser", user.getIdLong());
dm_call(crud, "cset", userConcept, litobjectarray("name", user.getName()));
return userConcept;
}
public MessageChannel getChannel(long channelID) {
return discord.getTextChannelById(channelID);
}
public void postInChannel(long channelID, String msg) {
postInChannel(channelID, msg, null);
}
public void postInChannel(long channelID, String msg, IVF1 onPost) {
if (channelID == 0)
return;
postInChannel(getChannel(channelID), msg, onPost);
}
public void uploadFileInChannel(long channelID, File file, String fileName, String msg, IVF1 onPost) {
if (channelID == 0)
return;
uploadFileInChannel(getChannel(channelID), file, fileName, msg, onPost);
}
public void postInChannel(MessageChannel channel, String msg, IVF1 onPost) {
String originalMsg = msg;
msg = shortenForDiscord(msg);
if (empty(msg))
return;
String postID = (String) (dm_call(gazelle_postedLinesCRUD(), "postingLine", channel.getId(), msg));
print("Posting in channel " + channel + ": " + msg);
pcallFAll(onPostedInChannel, channel, msg);
MessageAction a = channel.sendMessage(msg);
if (msg != originalMsg)
a.addFile(toUtf8(originalMsg), genericTextFileName());
a.queue(m -> msgPosted(m, onPost, postID), onQueueError);
}
public String genericTextFileName() {
return ymd_minus_hms() + ".txt";
}
public void msgPosted(Message m, IVF1 onPost, String postID) {
AutoCloseable __32 = enter();
try {
if (nempty(postID))
dm_call(gazelle_postedLinesCRUD(), "donePosting", postID, "discord msg " + m.getId());
long msgId = m.getIdLong();
print("I sent msg: " + msgId);
pcallF(onPost, m);
} finally {
_close(__32);
}
}
public void postInChannel(String channel, String msg) {
long id = dm_discord_channelID(channel);
if (id == 0)
throw fail("Channel not found: " + channel);
postInChannel(id, msg);
}
public void postInChannel(MessageChannel channel, String msg) {
postInChannel(channel, msg, null);
}
public void postImage(Map msgMap, String url) {
postImage(msgMap, url, "");
}
public void postImage(Map msgMap, String url, String description) {
postImage((MessageChannel) get("channel", msgMap), url, description);
}
public void postImage(MessageChannel channel, String url, String description) {
channel.sendMessage(new EmbedBuilder().setImage(absoluteURL(url)).setDescription(unnull(description)).setColor(discordImageEmbedMysteriousLineColor).build()).queue(null, onQueueError);
}
public void editMessage(long channelID, long msgID, String text) {
getChannel(channelID).editMessageById(str(msgID), text).queue(null, onQueueError);
}
public void sendPM(long userID, String _text) {
String text = shortenForDiscord(_text);
if (empty(text))
return;
print("Sending PM to " + userID + ": " + text);
discord.getUserById(userID).openPrivateChannel().queue(channel -> {
channel.sendMessage(text).queue(null, onQueueError);
}, onQueueError);
print("PM queued");
}
public void reply(Map msgMap, String text) {
reply(msgMap, text, null);
}
public void reply(Map msgMap, String text, Object onPost) {
if (empty(text = trim(text)))
return;
postInChannel((MessageChannel) msgMap.get("channel"), text, toIVF1(onPost));
}
public void iAmTyping(Map msgMap) {
try {
((MessageChannel) msgMap.get("channel")).sendTyping().queue(null, onQueueError);
} catch (Throwable __e) {
_handleException(__e);
}
}
public String startKeepAliveModule() {
AutoCloseable __33 = enter();
try {
return dm_discord_startKeepAliveModule(module());
} finally {
_close(__33);
}
}
public boolean reactToUser(User user) {
boolean bot = user.isBot();
if (bot && !reactToBots)
return false;
if (user.getIdLong() == discordBotID)
return false;
return true;
}
public void uploadFileInChannel(MessageChannel channel, File file, String fileName, String msg, IVF1 onPost) {
msg = shortenForDiscord(msg);
MessageAction a = empty(msg) ? channel.sendFile(file, fileName) : channel.sendMessage(msg).addFile(file, fileName);
a.queue(m -> msgPosted(m, onPost, null), onQueueError);
}
public void uploadFileInChannel(MessageChannel channel, byte[] data, String fileName, String msg, IVF1 onPost) {
msg = shortenForDiscord(msg);
MessageAction a = empty(msg) ? channel.sendFile(data, fileName) : channel.sendMessage(msg).addFile(data, fileName);
a.queue(m -> msgPosted(m, onPost, null), onQueueError);
}
public void uploadFileInChannel(long channelID, byte[] data, String fileName, String msg, IVF1 onPost) {
uploadFileInChannel(getChannel(channelID), data, fileName, msg, onPost);
}
public void queue(RestAction action) {
action.queue(null, onQueueError);
}
public boolean discordEnabled() {
return enabled;
}
public boolean printToModule() {
return true;
}
public boolean discordHopperMetaCmdsEnabled = false;
public long preferredChannelID;
transient public double minutesToKeepRecordedAnswers = 60.0;
public List recordedAnswers = syncList();
static public class RecordedAnswer {
public long timestamp;
public long questionMsgID, answerMsgID, channelID;
public String questionText, answerText;
public String toString() {
return stdToString(this);
}
}
static public boolean _switchableField_verboseEvents = true;
transient public boolean verboseEvents = false;
transient public List onDiscordStarted = new ArrayList();
transient public List> onDiscordEvent = syncList();
public ListenerAdapter genericListener = new ListenerAdapter() {
public void onGenericEvent(Event e) {
AutoCloseable __0 = enter();
try {
if (verboseEvents)
print("Discord event: " + e);
pcallFAll(onDiscordEvent, e);
} finally {
_close(__0);
}
}
};
public void onDiscordEvent(IVF1 e) {
onDiscordEvent.add(e);
}
public void enhanceFrame(Container f) {
super.enhanceFrame(f);
internalFramePopupMenuItem(f, "Start keep-alive module", runnableThread(new Runnable() {
public void run() {
try {
startKeepAliveModule();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startKeepAliveModule();";
}
}));
minFrameSize(f, 300, 300);
}
public void start() {
super.start();
startThread("Start", new Runnable() {
public void run() {
try {
AutoCloseable __1 = enter();
try {
try {
init();
startMe();
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __1 = enter(); try { try {\r\n init();\r\n startMe();\r\n } ca...";
}
});
}
public void startMe() {
dm_vmBus_onMessage_q("incomingDiscordMessage", new VF1() {
public void get(Map map) {
try {
if (!enabled)
return;
Object module = map.get("module");
if (!dm_isMe(module))
return;
String s = getString("content", map);
long channelID = toLong(map.get("channelID"));
if (channelID != 0 && preferredChannelID == 0)
setField("preferredChannelID", channelID);
cleanRecordedAnswers();
String answer = answer(s, map);
sendReply(map, answer);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!enabled) ret;\r\n O module = map.get('module);\r\n if (!dm_isMe(mo...";
}
});
startDiscord();
discord.addEventListener(genericListener);
print("onDiscordStarted=" + onDiscordStarted);
pcallFAll(onDiscordStarted);
}
public void sendReply(Map map, String answer) {
if (empty(answer))
return;
cleanRecordedAnswers();
RecordedAnswer a = new RecordedAnswer();
if (minutesToKeepRecordedAnswers > 0) {
a.timestamp = now();
a.questionMsgID = getLong("msgID", map);
a.channelID = getLong("channelID", map);
a.questionText = getString("content", map);
a.answerText = answer;
print("Recording answer : " + a);
recordedAnswers.add(a);
change();
}
dm_rcall("reply", map.get("module"), map, answer, (IVF1) msg -> {
a.answerMsgID = rcall_long("getIdLong", msg);
change();
});
}
public String answer(String s, Map map) {
if (discordHopperMetaCmdsEnabled && eq(s, "!bot count"))
return lstr(dm_activeDiscordTokens());
List tokens = extractPossibleDiscordTokens(s);
for (String token : unnull(tokens)) {
if (getLong("guildID", map) != 0)
return "Send tokens only in private messages!!";
String answer = "That's a Discord token!";
if (contains(concatLists((List>) vmBus_queryAll("activeDiscordTokens")), token))
answer += " And I'm there already.";
else {
answer += " Jumping there!!";
dm_showNewModuleWithParams(dm_moduleLibID(), "discordToken", token);
}
reply(map, answer);
}
return null;
}
public String atSelf() {
return discordAt(discordBotID);
}
public void onDiscordStarted(Runnable r) {
onDiscordStarted.add(r);
}
public User getSelfUser() {
return discord.getSelfUser();
}
public void init() {
dm_watchField("discordToken", new Runnable() {
public void run() {
try {
if (nempty(discordToken))
dm_reloadModule();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (nempty(discordToken)) dm_reloadModule()";
}
});
dm_watchField("enabled", new Runnable() {
public void run() {
try {
if (nempty(discordToken))
dm_reloadModule();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (nempty(discordToken)) dm_reloadModule()";
}
});
}
public void cleanRecordedAnswers() {
RecordedAnswer a;
boolean change = false;
synchronized (recordedAnswers) {
while ((a = first(recordedAnswers)) != null && elapsedMinutes_timestamp(a.timestamp) > minutesToKeepRecordedAnswers) {
print("Removing old answer: " + a);
recordedAnswers.remove(a);
}
change = true;
}
if (change)
change();
}
public JComponent visualize() {
JComponent _c = super.visualize();
if (empty(discordToken))
containerAddFirst(buttons, jThreadedButton("Give me a token!", new Runnable() {
public void run() {
try {
AutoCloseable __2 = enter();
try {
dm_stringFieldDialog("discordToken");
} finally {
_close(__2);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __2 = enter(); try { dm_stringFieldDialog discordToken();\r\n ...";
}
}));
addToContainer(buttons, jPopDownButton_noText("Export all my data...", runnableThread(new Runnable() {
public void run() {
try {
dm_exportStructureToTextFileDialog(module());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_exportStructureToTextFileDialog(module())";
}
}), "Import all my data...", runnableThread(new Runnable() {
public void run() {
try {
dm_importStructureFromTextFileDialog(module());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "dm_importStructureFromTextFileDialog(module())";
}
})));
return _c;
}
public boolean warnOnDelete() {
return true;
}
public String migrateToType(String moduleLibID) {
String moduleID = assertNotNull(dm_showNewModuleWithParams(moduleLibID, "discordToken", discordToken));
print("Migrated to new module " + moduleID + ", disabling me");
setEnabled(false);
dm_reload();
return moduleID;
}
}
static public interface IVF1 {
public void get(A a);
}
static public class Pair implements Comparable> {
public A a;
public B b;
public Pair() {
}
public Pair(A a, B b) {
this.b = b;
this.a = a;
}
public int hashCode() {
return hashCodeFor(a) + 2 * hashCodeFor(b);
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Pair))
return false;
Pair t = (Pair) o;
return eq(a, t.a) && eq(b, t.b);
}
public String toString() {
return "<" + a + ", " + b + ">";
}
public int compareTo(Pair p) {
if (p == null)
return 1;
int i = ((Comparable ) a).compareTo(p.a);
if (i != 0)
return i;
return ((Comparable) b).compareTo(p.b);
}
}
abstract static public class DynPrintLogAndEnabled extends DynPrintLog {
volatile public boolean enabled = true;
transient public JPanel buttons;
public JComponent visualize() {
return dm_visualizeWithEnabled(super.visualize());
}
public JComponent dm_visualizeWithEnabled(JComponent main) {
return centerAndSouthWithMargins(main, buttons = jrightalignedline(dm_fieldCheckBox("enabled")));
}
public void setEnabled(boolean b) {
setField("enabled", b);
}
}
abstract static public class DynPrintLog extends DynModule {
transient public JFastLogView_noWrap printLogView;
transient public Lock updatePrintLog_lock = lock();
transient public StringBuffer actualPrintLog;
public JComponent visualize() {
JComponent section = jSection("Log", jscroll_copyBackground(printLogView = jFastLogView_noWrap(getPrintLog())));
componentPopupMenuItem(section, "Clear", new Runnable() {
public void run() {
try {
AutoCloseable __3 = enter();
try {
dm_clearModulePrintLog();
} finally {
_close(__3);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "temp enter(); dm_clearModulePrintLog();";
}
});
return awtEvery(section, 500, new Runnable() {
public void run() {
try {
updatePrintLog();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "updatePrintLog();";
}
});
}
public void updatePrintLog() {
Lock __0 = updatePrintLog_lock;
lock(__0);
try {
JFastLogView_noWrap _view = printLogView;
if (_view == null)
return;
if (_view.setText(getPrintLog())) {
scrollAllTheWayDown(_view);
awtLater(100, new Runnable() {
public void run() {
try {
scrollAllTheWayDown(_view);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "scrollAllTheWayDown(_view)";
}
});
}
} finally {
unlock(__0);
}
}
public JFastLogView_noWrap myPrintLogComponent() {
return printLogView;
}
public void enableWordWrap() {
}
public String getPrintLog() {
if (actualPrintLog == null) {
if (printToModule())
actualPrintLog = _printLog;
else
actualPrintLog = liveLocalPrintLog_realMC(this);
}
return str(actualPrintLog);
}
}
static public class JFastLogView_noWrap extends JComponent implements Scrollable {
public List lines = syncList();
public boolean endsWithNewLine, verbose;
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return 20;
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return (direction == SwingConstants.HORIZONTAL ? visibleRect.width : visibleRect.height) * 5 / 6;
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public boolean getScrollableTracksViewportHeight() {
return false;
}
public void paint(Graphics g) {
int w = getWidth(), h = getHeight();
g.setColor(getBackground());
g.fillRect(0, 0, w, h);
g.setColor(getForeground());
FontMetrics fm = componentFontMetrics(this);
int fh = fm.getHeight();
Rectangle clip = g.getClipBounds();
int start, end;
if (clip == null) {
start = 0;
end = l(lines);
} else {
start = max(0, clip.y / fh);
end = min(l(lines), idiv_ceil(clip.y + clip.height, fh));
}
int y = fm.getAscent() + start * fh;
for (int i = start; i < end; i++) {
String s = get(lines, i);
if (s != null)
g.drawString(s, 0, y);
y += fh;
}
}
public Dimension getPreferredSize() {
FontMetrics fm = componentFontMetrics(this);
if (fm == null)
return new Dimension(50, 50);
int fh = fm.getHeight();
int w = 0;
for (int i = 0; i < l(lines); i++) {
String s = get(lines, i);
w = max(w, fm.stringWidth(unnull(s)));
}
return new Dimension(w, fh * l(lines));
}
public JFastLogView_noWrap() {
}
public JFastLogView_noWrap(String text) {
setText(text);
}
{
componentPopupMenuItem(this, "Copy full text", new Runnable() {
public void run() {
try {
copyFullText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "copyFullText();";
}
});
}
public boolean setLines(Collection lines) {
List newList = asSyncList(lines);
if (eq(this.lines, newList))
return false;
this.lines = newList;
_revalidate(this);
return true;
}
public boolean setText(String text) {
endsWithNewLine = endsWithNewLine(text);
return setLines(lines(text));
}
public void append(String text) {
if (nempty(text))
setText(getText() + text);
}
public String getText() {
return lines_rtrimIf(!endsWithNewLine, cloneList(lines));
}
public void copyFullText() {
copyTextToClipboard(getText());
}
}
static abstract public class DynModule {
public String name, toolTip;
public PersistableThrowable _error;
public Map> mechLists;
public Map _persistenceInfo;
transient public Object _host;
transient public Map timers = newWeakHashMap();
transient public Set _resources = synchroHashSet();
transient public Lock lock;
transient public boolean persistOnChangedField = true;
transient public int changeCount;
transient public Object changeCountSync = new Object();
transient public List onChange;
transient public List onTransientChange;
transient public boolean verboseTimers = false;
transient public ReliableSingleThread rstUpdate;
transient public Set componentFieldsToKeep;
transient public Map transientGeneralMap = synchroHashMap();
transient public Q q;
transient public List onFieldChange;
transient public boolean _hasPreviousBounds = false;
transient public StringBuffer _printLog = new StringBuffer();
transient public boolean deleted = false;
public DynModule() {
dm_initErrorHandling();
setMainDesktopPane((JDesktopPane) getCreatorOpt("desktop"));
}
public boolean isVisible() {
return isTrue(getOpt(_host, "visible"));
}
public String moduleName() {
return name;
}
public void setModuleName(String name) {
String oldName = this.name;
if (!eq(name, oldName)) {
this.name = name;
possiblyInternalFrameTitle(vis(), name);
vmBus_send("moduleNameChange", this, oldName, name);
}
}
public void setModuleToolTip(String toolTip) {
this.toolTip = toolTip;
}
public JComponent vis() {
return (JComponent) getOpt(_host, "vis");
}
public A ownResource(A a) {
if (a != null)
_resources.add(a);
return a;
}
public A ownTimer(A timer) {
if (timer instanceof AutoCloseable)
ownResource((AutoCloseable) timer);
ownTimer(timer, "cancelTimerOrInterruptThread");
return timer;
}
public void ownTimer(Object timer, Object closerHelper) {
timers.put(timer, closerHelper);
}
public void singleTimer(java.util.Timer timer) {
stopAllTimers();
ownTimer(timer);
}
public void stopAllTimers() {
for (AutoCloseable resource : getAndClearList(_resources)) {
if (verboseTimers)
print("Releasing resource: " + resource);
try {
resource.close();
} catch (Throwable __e) {
_handleException(__e);
}
}
{
final Map __0 = getAndClearMap(timers);
for (Object timer : keys(__0)) {
Object closerHelper = __0.get(timer);
if (verboseTimers)
print("Stopping timer: " + closerHelper + " / " + timer);
pcallFInRealOrMyMC(this, closerHelper, timer);
}
}
}
public void cleanMeUp_dynModule() {
deleted = true;
stopAllTimers();
}
public void persistMe() {
synchronized (changeCountSync) {
++changeCount;
}
pcallFAll(onChange);
callOpt(_host, "_change");
updateMe();
}
public void fireChangeWithoutPersisting() {
pcallFAll(onChange);
}
public void fireTransientChange() {
pcallFAll(onTransientChange);
}
public void _change() {
persistMe();
}
public void change() {
persistMe();
}
public void updateMe() {
rstUpdate().trigger();
}
public void changeAndUpdate() {
_change();
updateMe();
}
public boolean setField(String name, Object value) {
AutoCloseable __4 = enter();
try {
{
try {
if (eq(get(this, name), value))
return false;
} catch (Throwable __e) {
_handleException(__e);
}
set(this, name, value);
}
pcallFAll(onFieldChange, name);
if (persistOnChangedField && !isFalse(mapGet(_persistenceInfo, name)))
_change();
return true;
} finally {
_close(__4);
}
}
public A setFieldAndReturn(String name, A value) {
setField(name, value);
return value;
}
public boolean setFields(Object... params) {
boolean change = false;
for (int i = 0; i < l(params); i += 2) if (setField((String) params[i], params[i + 1]))
change = true;
return change;
}
public void start() {
_hasPreviousBounds = dm_getBounds() != null;
if (hasMethod_onTypes(this, "onTopInput", String.class))
dm_onTopInput_q(new VF1() {
public void get(String s) {
try {
call(module(), "onTopInput", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "call(module(), 'onTopInput, s)";
}
});
}
public void revisualize() {
call(creator(), "revisualizeModule", _host);
}
public AutoCloseable enter() {
AutoCloseable c = tempSetThreadLocal(dm_currentModule_value, new WeakReference(this));
final Object realMC = getMainClass(this);
if (printToModule())
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(_printToModuleInterceptor()));
if (realMC != mc()) {
if (printToModule())
c = combineAutoCloseables(c, (AutoCloseable) callOpt(realMC, "tempInterceptPrintIfNotIntercepted", _printToModuleInterceptor()));
else
c = combineAutoCloseables(c, tempInterceptPrintIfNotIntercepted(new F1() {
public Boolean get(String s) {
try {
{
call(realMC, "print", s);
return false;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret false with call(realMC, 'print, s);";
}
}));
c = combineAutoCloseables(c, tempSetTL(realMC_tl(), realMC));
}
return c;
}
public F1 _printToModuleInterceptor() {
return new F1() {
public Boolean get(String s) {
try {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = _printLog;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (print_preprocess != null) s = (S) callF(print_preprocess, s);\r\n s = ...";
}
};
}
public boolean printToModule() {
return true;
}
public AutoCloseable enterAndLock() {
return combineAutoCloseables(enter(), tempLock(lock));
}
public boolean setError(Throwable e) {
setField("_error", persistableThrowable(e));
return true;
}
public void clearError() {
setField("_error", null);
}
public void onChange(Runnable r) {
Lock __1 = lock;
lock(__1);
try {
if (onChange == null)
onChange = synchroList();
addIfNotThere(onChange, r);
} finally {
unlock(__1);
}
}
public void onFieldChange(VF1 r) {
Lock __2 = lock;
lock(__2);
try {
if (onFieldChange == null)
onFieldChange = synchroList();
addIfNotThere(onFieldChange, r);
} finally {
unlock(__2);
}
}
public void onChangeAndNow(Runnable r) {
onChange(r);
callF(r);
}
public void onChangeAndNow(JComponent c, Object r) {
onUpdateAndNow(c, r);
}
public A onChange(A tc, Object r) {
onUpdate(tc, r);
return tc;
}
public void update() {
}
public void unvisualize() {
zeroAllFieldsOfTypeExcept(this, Component.class, componentFieldsToKeep);
}
public List menuItems() {
return null;
}
public void enhanceFrame(Container f) {
internalFramePopupMenuFromActions_threaded(f, menuItems());
String switchableFields = (String) (callOpt(this, "switchableFields"));
Set set = asLinkedHashSet(splitAtSpace(switchableFields));
Matches m = new Matches();
for (String field : allFields(this)) if (startsWith(field, "_switchableField_", m))
set.add(m.rest());
for (String field : set) {
Class type = fieldType(this, field);
if (eq(boolean.class, type))
dm_boolFieldMenuItem(f, field);
else if (eq(int.class, type))
dm_intFieldMenuItem(f, field);
else if (eq(double.class, type))
dm_doubleFieldMenuItem(f, field);
else if (eq(String.class, type))
dm_stringFieldMenuItem(f, field);
}
}
public ReliableSingleThread rstUpdate() {
if (rstUpdate == null)
rstUpdate = dm_rst(this, new Runnable() {
public void run() {
try {
AutoCloseable __5 = enter();
try {
update();
} finally {
_close(__5);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __5 = enter(); try { update(); } finally { _close(__5); }";
}
});
return rstUpdate;
}
public Q q() {
AutoCloseable __6 = enter();
try {
if (q == null) {
Lock __3 = lock;
lock(__3);
try {
if (q == null)
q = dm_startQ();
} finally {
unlock(__3);
}
}
return q;
} finally {
_close(__6);
}
}
public A withUpdate(A a) {
rstUpdate().trigger();
return a;
}
public DynModule module() {
return this;
}
public DynModule me() {
return this;
}
public JComponent visualize() {
return dm_noVisualisation();
}
public String programTitle_cache;
public String programTitle() {
if (programTitle_cache == null)
programTitle_cache = snippetTitle(programID(mainClass(this)));
return programTitle_cache;
}
public void doPersist(String field) {
_persistenceInfo = mapMinus(_persistenceInfo, field);
}
public void dontPersist(String field) {
_persistenceInfo = mapPlus(_persistenceInfo, "field", false);
}
public Appendable _actualPrintLog() {
return printToModule() ? _printLog : print_log;
}
}
static public void _registerTimer(java.util.Timer timer) {
_registerTimer_original(timer);
dm_currentModule().ownTimer(timer);
}
static public class Q implements AutoCloseable {
public String name = "Unnamed Queue";
public List q = synchroLinkedList();
public ReliableSingleThread rst = new ReliableSingleThread(new Runnable() {
public void run() {
try {
_run();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_run()";
}
});
volatile public boolean retired = false;
public Q() {
}
public Q(String name) {
this.name = name;
}
public void add(Runnable r) {
q.add(r);
_trigger();
}
public void addInFront(Runnable r) {
q.add(0, r);
_trigger();
}
public void _trigger() {
rst.name = name;
rst.go();
}
public void add(Object r) {
add(toRunnable(r));
}
public void _run() {
Runnable r;
while (licensed() && !retired && (r = syncPopFirst(q)) != null) {
try {
r.run();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
public void close() {
retired = true;
}
public void done() {
}
public boolean isEmpty() {
return q.isEmpty();
}
public int size() {
return q.size();
}
}
static public class ReliableSingleThread implements Runnable {
public Object runnable;
public boolean trigger = false;
public Thread thread;
public String name = "Single Thread";
public F0 enter;
public ReliableSingleThread(Object runnable) {
this.runnable = runnable;
}
public void trigger() {
go();
}
synchronized public void go() {
trigger = true;
if (!running()) {
AutoCloseable __0 = callF(enter);
try {
thread = startThread(name, new Runnable() {
public void run() {
try {
AutoCloseable __1 = callF(enter);
try {
_run();
} finally {
_close(__1);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __1 = callF(enter); try {\r\n _run();\r\n } finally { _...";
}
});
} finally {
_close(__0);
}
}
}
public void run() {
go();
}
public void get() {
go();
}
synchronized public boolean running() {
return thread != null;
}
public void triggerAndWait() {
trigger();
while (running()) sleep(1);
}
public void _run() {
while (licensed()) {
synchronized (this) {
if (!trigger) {
thread = null;
break;
}
trigger = false;
}
pcallF(runnable);
}
}
synchronized public void cancel() {
cancelAndInterruptThread(thread);
thread = null;
}
synchronized public boolean triggered() {
return trigger;
}
public void cleanMeUp() {
cancel();
}
}
static public class PersistableThrowable {
public String className;
public String msg;
public String stacktrace;
public PersistableThrowable() {
}
public PersistableThrowable(Throwable e) {
if (e == null)
className = "Crazy Null Error";
else {
className = getClassName(e).replace('/', '.');
msg = e.getMessage();
stacktrace = getStackTrace_noRecord(e);
}
}
public String toString() {
return nempty(msg) ? className + ": " + msg : className;
}
}
static abstract public class F1 {
abstract public B get(A a);
}
static abstract public class F0 {
abstract public A get();
}
static public List myInnerClasses_list = litlist("VF1", "VF2", "JSection", "Var", "TokCondition", "RightAlignedLine", "findCodeTokens_Matcher", "SimpleLiveValue", "ReliableSingleThread", "JFastLogView_noWrap", "DynServerAwareDiscordBot", "SingleComponentPanel", "DynModule", "Rect", "Pt", "F0", "F1", "IterableIterator", "F2", "Flag", "IF0", "CloseableIterableIterator", "IFieldsToList", "getOpt_Map", "IF2", "IF1", "structure_Data", "DynDiscordHopper", "IVF1", "IVF2", "IVar", "DynPrintLogAndEnabled", "_MethodCache", "LineBuffer", "Matches", "structure_ClassInfo", "LiveValue", "Dyn_FieldWatcher", "LetterLayout", "Q", "CriticalAction", "Lowest", "IResourceLoader", "DynTalkBot2", "Pair", "DynPrintLog", "BetterLabel", "componentPopupMenu_Adapter", "MRUCache", "DynamicObject", "PersistableThrowable", "Scored");
static public List myInnerClasses() {
return myInnerClasses_list;
}
static public DynModule dm_currentModule() {
return (DynModule) dm_current_generic();
}
static public void cancelTimerOrInterruptThread(Object timer) {
if (timer instanceof Thread && !(timer instanceof AutoCloseable))
interruptThread((Thread) timer);
else
cancelTimer(timer);
}
static public String discordAtPlusID(long userID) {
return userID == 0 ? "unknown person" : "<@" + userID + "> (" + userID + ")";
}
static public List ll(A... a) {
ArrayList l = new ArrayList(a.length);
if (a != null)
for (A x : a) l.add(x);
return l;
}
static public boolean eq(Object a, Object b) {
return a == b || (a == null ? b == null : b != null && a.equals(b));
}
static public int boostHashCombine(int a, int b) {
return a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2));
}
static public int _hashCode(Object a) {
return a == null ? 0 : a.hashCode();
}
static public void mapPut(Map map, A key, B value) {
if (map != null && key != null && value != null)
map.put(key, value);
}
static public A nu(Class c, Object... values) {
A a = nuObject(c);
setAll(a, values);
return a;
}
static public void change() {
callOpt(getOptMC("mainConcepts"), "allChanged");
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF1 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF1 () {
public void get(final A a) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final VF2 onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF2 () {
public void get(final A a, final B b) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage, a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage, a, b);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage, a, b);";
}
});
}
static public AutoCloseable dm_vmBus_onMessage_q(final String msg, final Runnable onMessage) {
final DynModule m = dm_current_mandatory();
return dm_vmBus_onMessage(msg, new VF1 () {
public void get(final A a) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(onMessage);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(onMessage);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(onMessage);";
}
});
}
static volatile public StringBuffer local_log = new StringBuffer();
static volatile public Appendable print_log = local_log;
static volatile public int print_log_max = 1024 * 1024;
static volatile public int local_log_max = 100 * 1024;
static public boolean print_silent = false;
static public Object print_byThread_lock = new Object();
static volatile public ThreadLocal print_byThread;
static volatile public Object print_allThreads;
static volatile public Object print_preprocess;
static public void print() {
print("");
}
static public A print(String s, A o) {
print((endsWithLetterOrDigit(s) ? s + ": " : s) + o);
return o;
}
static public A print(A o) {
ping_okInCleanUp();
if (print_silent)
return o;
String s = String.valueOf(o) + "\n";
print_noNewLine(s);
return o;
}
static public void print_noNewLine(String s) {
Object f = getThreadLocal(print_byThread_dontCreate());
if (f == null)
f = print_allThreads;
if (f != null)
if (isFalse(f instanceof F1 ? ((F1) f).get(s) : callF(f, s)))
return;
print_raw(s);
}
static public void print_raw(String s) {
if (print_preprocess != null)
s = (String) callF(print_preprocess, s);
s = fixNewLines(s);
Appendable loc = local_log;
Appendable buf = print_log;
int loc_max = print_log_max;
if (buf != loc && buf != null) {
print_append(buf, s, print_log_max);
loc_max = local_log_max;
}
if (loc != null)
print_append(loc, s, loc_max);
System.out.print(s);
}
static public void print_autoRotate() {
}
static public long getLong(Object o, String field) {
return toLong(getOpt(o, field));
}
static public long getLong(String field, Object o) {
return getLong(o, field);
}
static public RuntimeException rethrow(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
throw t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public RuntimeException rethrow(String msg, Throwable t) {
throw new RuntimeException(msg, t);
}
static public List synchroList() {
return Collections.synchronizedList(new ArrayList ());
}
static public List synchroList(List l) {
return Collections.synchronizedList(l);
}
static public Map synchroMap() {
return synchroHashMap();
}
static public Map synchroMap(Map map) {
return Collections.synchronizedMap(map);
}
static public long longPar(String name, Object... params) {
return toLong(optPar(name, params));
}
static public boolean empty(Collection c) {
return c == null || c.isEmpty();
}
static public boolean empty(CharSequence s) {
return s == null || s.length() == 0;
}
static public boolean empty(Map map) {
return map == null || map.isEmpty();
}
static public boolean empty(Object[] o) {
return o == null || o.length == 0;
}
static public boolean empty(Object o) {
if (o instanceof Collection)
return empty((Collection) o);
if (o instanceof String)
return empty((String) o);
if (o instanceof Map)
return empty((Map) o);
if (o instanceof Object[])
return empty((Object[]) o);
if (o instanceof byte[])
return empty((byte[]) o);
if (o == null)
return true;
throw fail("unknown type for 'empty': " + getType(o));
}
static public boolean empty(Iterator i) {
return i == null || !i.hasNext();
}
static public boolean empty(float[] a) {
return a == null || a.length == 0;
}
static public boolean empty(int[] a) {
return a == null || a.length == 0;
}
static public boolean empty(long[] a) {
return a == null || a.length == 0;
}
static public boolean empty(byte[] a) {
return a == null || a.length == 0;
}
static public boolean empty(short[] a) {
return a == null || a.length == 0;
}
static public boolean empty(File f) {
return getFileSize(f) == 0;
}
static public String dropPrefixICTrim_orNull(String prefix, String s) {
return swic(s, prefix) ? trim(s.substring(l(prefix))) : null;
}
static public String quote(Object o) {
if (o == null)
return "null";
return quote(str(o));
}
static public String quote(String s) {
if (s == null)
return "null";
StringBuilder out = new StringBuilder((int) (l(s) * 1.5 + 2));
quote_impl(s, out);
return out.toString();
}
static public void quote_impl(String s, StringBuilder out) {
out.append('"');
int l = s.length();
for (int i = 0; i < l; i++) {
char c = s.charAt(i);
if (c == '\\' || c == '"')
out.append('\\').append(c);
else if (c == '\r')
out.append("\\r");
else if (c == '\n')
out.append("\\n");
else if (c == '\0')
out.append("\\0");
else
out.append(c);
}
out.append('"');
}
static public List replace(List l, A a, A b) {
for (int i = 0; i < l(l); i++) if (eq(l.get(i), a))
l.set(i, b);
return l;
}
static public List replace(A a, A b, List l) {
return replace(l, a, b);
}
static public String replace(String s, String a, String b) {
return s == null ? null : a == null || b == null ? s : s.replace(a, b);
}
static public String replace(String s, char a, char b) {
return s == null ? null : s.replace(a, b);
}
static public String dropPunctuation3_withAGIBlue(boolean useAGIBlue, String s) {
return useAGIBlue ? dropPunctuation3_withAGIBlue(s) : dropPunctuation3(s);
}
static public String dropPunctuation3_withAGIBlue(String s) {
if (!agiBlue_validPageName(s))
return dropPunctuation3(s);
String y = dropPunctuation3_cache.get(s);
if (y != null)
return y;
{
String __1 = agiBlue_lookupInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation");
if (!empty(__1))
return __1;
}
y = dropPunctuation3(s);
agiBlue_postInSlice_pcall("xwxxvxozhdlwsxzj", s, "dropPunctuation", y);
return y;
}
static public String trim(String s) {
return s == null ? null : s.trim();
}
static public String trim(StringBuilder buf) {
return buf.toString().trim();
}
static public String trim(StringBuffer buf) {
return buf.toString().trim();
}
static public String simpleSpaces_noTok(String s) {
return s == null ? null : s.replaceAll("\\s+", " ");
}
static public boolean endsWithLetterOrDigit(String s) {
return s != null && s.length() > 0 && Character.isLetterOrDigit(s.charAt(s.length() - 1));
}
static public void lock(Lock lock) {
try {
ping();
if (lock == null)
return;
try {
lock.lockInterruptibly();
} catch (InterruptedException e) {
print("Locking interrupted! I probably deadlocked, oops.");
printStackTrace(e);
rethrow(e);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void lock(Lock lock, String msg) {
print("Locking: " + msg);
lock(lock);
}
static public void lock(Lock lock, String msg, long timeout) {
print("Locking: " + msg);
lockOrFail(lock, timeout);
}
static public ReentrantLock lock() {
return fairLock();
}
static public boolean eqicOneOf(String s, String... l) {
for (String x : l) if (eqic(s, x))
return true;
return false;
}
static public String nextGenBotsDiscordInvite() {
return "https://discord.gg/SEAjPqk";
}
static public String snippetLink(String id) {
return empty(id) ? id : "http://code.botcompany.de/" + parseSnippetID(id);
}
static public String programID() {
return getProgramID();
}
static public String programID(Object o) {
return getProgramID(o);
}
static public boolean swic_trim(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { trim(substring(a, l(b))) };
return true;
}
static public boolean setAdd(Collection c, A a) {
if (c == null || c.contains(a))
return false;
c.add(a);
return true;
}
static public long parseFirstLong(String s) {
return parseLong(jextract("", s));
}
static public String n2(long l) {
return formatWithThousands(l);
}
static public String n2(Collection l) {
return n2(l(l));
}
static public String n2(double l, String singular) {
return n2(l, singular, singular + "s");
}
static public String n2(double l, String singular, String plural) {
if (fraction(l) == 0)
return n2((long) l, singular, plural);
else
return l + " " + plural;
}
static public String n2(long l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(long l, String singular) {
return n_fancy2(l, singular, singular + "s");
}
static public String n2(Collection l, String singular) {
return n2(l(l), singular);
}
static public String n2(Collection l, String singular, String plural) {
return n_fancy2(l, singular, plural);
}
static public String n2(Map m, String singular, String plural) {
return n_fancy2(m, singular, plural);
}
static public String n2(Map m, String singular) {
return n2(l(m), singular);
}
static public String n2(Object[] a, String singular) {
return n2(l(a), singular);
}
static public String n2(Object[] a, String singular, String plural) {
return n_fancy2(a, singular, plural);
}
static public int l(Object[] a) {
return a == null ? 0 : a.length;
}
static public int l(boolean[] a) {
return a == null ? 0 : a.length;
}
static public int l(byte[] a) {
return a == null ? 0 : a.length;
}
static public int l(short[] a) {
return a == null ? 0 : a.length;
}
static public int l(long[] a) {
return a == null ? 0 : a.length;
}
static public int l(int[] a) {
return a == null ? 0 : a.length;
}
static public int l(float[] a) {
return a == null ? 0 : a.length;
}
static public int l(double[] a) {
return a == null ? 0 : a.length;
}
static public int l(char[] a) {
return a == null ? 0 : a.length;
}
static public int l(Collection c) {
return c == null ? 0 : c.size();
}
static public int l(Iterator i) {
return iteratorCount_int_close(i);
}
static public int l(Map m) {
return m == null ? 0 : m.size();
}
static public int l(CharSequence s) {
return s == null ? 0 : s.length();
}
static public long l(File f) {
return f == null ? 0 : f.length();
}
static public int l(Object o) {
return o == null ? 0 : o instanceof String ? l((String) o) : o instanceof Map ? l((Map) o) : o instanceof Collection ? l((Collection) o) : o instanceof Object[] ? l((Object[]) o) : o instanceof boolean[] ? l((boolean[]) o) : o instanceof byte[] ? l((byte[]) o) : o instanceof char[] ? l((char[]) o) : o instanceof short[] ? l((short[]) o) : o instanceof int[] ? l((int[]) o) : o instanceof float[] ? l((float[]) o) : o instanceof double[] ? l((double[]) o) : o instanceof long[] ? l((long[]) o) : (Integer) call(o, "size");
}
static public boolean eqic(String a, String b) {
if ((a == null) != (b == null))
return false;
if (a == null)
return true;
return a.equalsIgnoreCase(b);
}
static public boolean eqic(char a, char b) {
if (a == b)
return true;
char u1 = Character.toUpperCase(a);
char u2 = Character.toUpperCase(b);
if (u1 == u2)
return true;
return Character.toLowerCase(u1) == Character.toLowerCase(u2);
}
static public void remove(List l, int i) {
if (l != null && i >= 0 && i < l(l))
l.remove(i);
}
static public void remove(Collection l, A a) {
if (l != null)
l.remove(a);
}
static public void unlock(Lock lock, String msg) {
if (lock == null)
return;
print("Unlocking: " + msg);
lock.unlock();
}
static public void unlock(Lock lock) {
if (lock == null)
return;
lock.unlock();
}
static public String joinWithComma(Collection c) {
return join(", ", c);
}
static public String joinWithComma(String... c) {
return join(", ", c);
}
static public String joinWithComma(Pair p) {
return p == null ? "" : joinWithComma(str(p.a), str(p.b));
}
static public List map(Iterable l, Object f) {
return map(f, l);
}
static public List map(Object f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (Object o : l) x.add(callF(f, o));
return x;
}
static public List map(Iterable l, F1 f) {
return map(f, l);
}
static public List map(F1 f, Iterable l) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(callF(f, o));
return x;
}
static public List map(IF1 f, Iterable l) {
return map(l, f);
}
static public List map(Iterable l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(IF1 f, A[] l) {
return map(l, f);
}
static public List map(A[] l, IF1 f) {
List x = emptyList(l);
if (l != null)
for (A o : l) x.add(f.get(o));
return x;
}
static public List map(Object f, Object[] l) {
return map(f, asList(l));
}
static public List map(Object[] l, Object f) {
return map(f, l);
}
static public List map(Object f, Map map) {
return map(map, f);
}
static public List map(Map map, Object f) {
List x = new ArrayList();
if (map != null)
for (Object _e : map.entrySet()) {
Map.Entry e = (Map.Entry) _e;
x.add(callF(f, e.getKey(), e.getValue()));
}
return x;
}
static public List map(Map map, IF2 f) {
return map(map, (Object) f);
}
static public String lines(Iterable lines) {
return fromLines(lines);
}
static public String lines(Object[] lines) {
return fromLines(asList(lines));
}
static public List lines(String s) {
return toLines(s);
}
static public boolean contains(Collection c, Object o) {
return c != null && c.contains(o);
}
static public boolean contains(Object[] x, Object o) {
if (x != null)
for (Object a : x) if (eq(a, o))
return true;
return false;
}
static public boolean contains(String s, char c) {
return s != null && s.indexOf(c) >= 0;
}
static public boolean contains(String s, String b) {
return s != null && s.indexOf(b) >= 0;
}
static public boolean contains(BitSet bs, int i) {
return bs != null && bs.get(i);
}
static public A optPar(ThreadLocal tl, A defaultValue) {
A a = tl.get();
if (a != null) {
tl.set(null);
return a;
}
return defaultValue;
}
static public A optPar(ThreadLocal tl) {
return optPar(tl, null);
}
static public Object optPar(Object[] params, String name) {
return optParam(params, name);
}
static public Object optPar(String name, Object[] params) {
return optParam(params, name);
}
static public Object optPar(String name, Map params) {
return optParam(name, params);
}
static public A optPar(Object[] params, String name, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public A optPar(String name, Object[] params, A defaultValue) {
return optParam(params, name, defaultValue);
}
static public String structure_nullingInstancesOfClass(Class c, Object o) {
if (c == null)
return structure(o);
structure_Data data = new structure_Data();
structure_ClassInfo info = new structure_ClassInfo();
info.special = info.nullInstances = true;
data.infoByClass.put(c, info);
return structure(o, data);
}
static public Class> _getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class _getClass(Object o) {
return o == null ? null : o instanceof Class ? (Class) o : o.getClass();
}
static public Class _getClass(Object realm, String name) {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
}
static public boolean containsDiscordToken(String s) {
return regexpFind(discordTokenRegexp(), s);
}
static public String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
static public String jda_selfUserName(JDA jda) {
return jda_selfUser(jda).getName();
}
static public String ymd_minus_hms() {
return ymd() + "-" + hms();
}
static public File programFile(String name) {
return prepareProgramFile(name);
}
static public File programFile(String progID, String name) {
return prepareProgramFile(progID, name);
}
static public File createZipFileWithSingleTextFile(File zipFile, String name, String text) {
ZipOutputStream outZip = newZipOutputStream(zipFile);
try {
zip_addTextFile(outZip, name, text);
return zipFile;
} finally {
_close(outZip);
}
}
static public String unquote(String s) {
if (s == null)
return null;
if (startsWith(s, '[')) {
int i = 1;
while (i < s.length() && s.charAt(i) == '=') ++i;
if (i < s.length() && s.charAt(i) == '[') {
String m = s.substring(1, i);
if (s.endsWith("]" + m + "]"))
return s.substring(i + 1, s.length() - i - 1);
}
}
if (s.length() > 1) {
char c = s.charAt(0);
if (c == '\"' || c == '\'') {
int l = endsWith(s, c) ? s.length() - 1 : s.length();
StringBuilder sb = new StringBuilder(l - 1);
for (int i = 1; i < l; i++) {
char ch = s.charAt(i);
if (ch == '\\') {
char nextChar = (i == l - 1) ? '\\' : s.charAt(i + 1);
if (nextChar >= '0' && nextChar <= '7') {
String code = "" + nextChar;
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
if ((i < l - 1) && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '7') {
code += s.charAt(i + 1);
i++;
}
}
sb.append((char) Integer.parseInt(code, 8));
continue;
}
switch(nextChar) {
case '\"':
ch = '\"';
break;
case '\\':
ch = '\\';
break;
case 'b':
ch = '\b';
break;
case 'f':
ch = '\f';
break;
case 'n':
ch = '\n';
break;
case 'r':
ch = '\r';
break;
case 't':
ch = '\t';
break;
case '\'':
ch = '\'';
break;
case 'u':
if (i >= l - 5) {
ch = 'u';
break;
}
int code = Integer.parseInt("" + s.charAt(i + 2) + s.charAt(i + 3) + s.charAt(i + 4) + s.charAt(i + 5), 16);
sb.append(Character.toChars(code));
i += 5;
continue;
default:
ch = nextChar;
}
i++;
}
sb.append(ch);
}
return sb.toString();
}
}
return s;
}
static public A get(List l, int idx) {
return l != null && idx >= 0 && idx < l(l) ? l.get(idx) : null;
}
static public A get(A[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : null;
}
static public boolean get(boolean[] l, int idx) {
return idx >= 0 && idx < l(l) ? l[idx] : false;
}
static public Object get(Object o, String field) {
try {
if (o == null)
return null;
if (o instanceof Class)
return get((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
Field f = getOpt_findField(o.getClass(), field);
if (f != null) {
makeAccessible(f);
return f.get(o);
}
if (o instanceof DynamicObject)
return ((DynamicObject) o).fieldValues.get(field);
} catch (Exception e) {
throw asRuntimeException(e);
}
throw new RuntimeException("Field '" + field + "' not found in " + o.getClass().getName());
}
static public Object get_raw(String field, Object o) {
return get_raw(o, field);
}
static public Object get_raw(Object o, String field) {
try {
if (o == null)
return null;
Field f = get_findField(o.getClass(), field);
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object get(Class c, String field) {
try {
Field f = get_findStaticField(c, field);
makeAccessible(f);
return f.get(null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field get_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field get_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public Object get(String field, Object o) {
return get(o, field);
}
static public String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static public String formatSnippetID(long id) {
return "#" + id;
}
static public String fsi(String id) {
return formatSnippetID(id);
}
static public List quoteAll(Collection l) {
List x = new ArrayList();
for (String s : l) x.add(quote(s));
return x;
}
static public ArrayList asList(A[] a) {
return a == null ? new ArrayList () : new ArrayList (Arrays.asList(a));
}
static public ArrayList asList(int[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (int i : a) l.add(i);
return l;
}
static public ArrayList asList(float[] a) {
if (a == null)
return null;
ArrayList l = emptyList(a.length);
for (float i : a) l.add(i);
return l;
}
static public ArrayList asList(Iterable s) {
if (s instanceof ArrayList)
return (ArrayList) s;
ArrayList l = new ArrayList();
if (s != null)
for (A a : s) l.add(a);
return l;
}
static public ArrayList asList(Enumeration e) {
ArrayList l = new ArrayList();
if (e != null)
while (e.hasMoreElements()) l.add(e.nextElement());
return l;
}
static public ArrayList toList(A[] a) {
return asList(a);
}
static public ArrayList toList(int[] a) {
return asList(a);
}
static public ArrayList toList(Set s) {
return asList(s);
}
static public ArrayList toList(Iterable s) {
return asList(s);
}
static public boolean arraysEqual(Object[] a, Object[] b) {
if (a.length != b.length)
return false;
for (int i = 0; i < a.length; i++) if (neq(a[i], b[i]))
return false;
return true;
}
static public boolean set_trueIfChanged(Object o, String field, Object value) {
if (eq(get(o, field), value))
return false;
set(o, field, value);
return true;
}
static public long toLong(Object o) {
if (o instanceof Number)
return ((Number) o).longValue();
if (o instanceof String)
return parseLong((String) o);
return 0;
}
static public boolean nempty(Collection c) {
return !empty(c);
}
static public boolean nempty(CharSequence s) {
return !empty(s);
}
static public boolean nempty(Object[] o) {
return !empty(o);
}
static public boolean nempty(byte[] o) {
return !empty(o);
}
static public boolean nempty(int[] o) {
return !empty(o);
}
static public boolean nempty(Map m) {
return !empty(m);
}
static public boolean nempty(Iterator i) {
return i != null && i.hasNext();
}
static public boolean nempty(Object o) {
return !empty(o);
}
static public String lines_rtrim(Collection lines) {
return rtrim_fromLines(lines);
}
static public List nempties(Collection c) {
return filterNempty(c);
}
static public A pairA(Pair p) {
return p == null ? null : p.a;
}
static public Pair syncGetOrCreate2(Map map, A key, Class extends B> c) {
try {
synchronized (map) {
B b = map.get(key);
if (b == null) {
map.put(key, b = c.newInstance());
return pair(b, true);
}
return pair(b, false);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Pair syncGetOrCreate2(Class extends B> c, Map map, A key) {
return syncGetOrCreate2(map, key, c);
}
static public Pair syncGetOrCreate2(Map map, A key, F0 f) {
try {
synchronized (map) {
B b = map.get(key);
if (b == null) {
map.put(key, b = callF(f));
return pair(b, true);
}
return pair(b, false);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Pair syncGetOrCreate2(Map map, A key, IF0 f) {
try {
synchronized (map) {
B b = map.get(key);
if (b == null) {
map.put(key, b = f.get());
return pair(b, true);
}
return pair(b, false);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Pair pair(A a, B b) {
return new Pair(a, b);
}
static public Pair pair(A a) {
return new Pair(a, a);
}
static public int countValuesWhere_sync(Map map, Object... data) {
if (map == null)
return 0;
synchronized (map) {
return countWhere(values(map), data);
}
}
static public A keyForValue_sync(B value, Map map) {
return keyForValue_sync(map, value);
}
static public A keyForValue_sync(Map map, B value) {
if (map == null || value == null)
return null;
synchronized (map) {
return keyForValue(map, value);
}
}
static public List tlft(String s) {
return toLinesFullTrim(s);
}
static public List tlft(File f) {
return toLinesFullTrim(f);
}
static public List syncList() {
return synchroList();
}
static public List syncList(List l) {
return synchroList(l);
}
static public String stdToString(Object o) {
return standard_toString(o);
}
static public void pcallFAll(Collection l, Object... args) {
if (l != null)
for (Object f : cloneList(l)) pcallF(f, args);
}
static public void pcallFAll(Iterator it, Object... args) {
while (it.hasNext()) pcallF(it.next(), args);
}
static public void _close(AutoCloseable c) {
if (c != null)
try {
c.close();
} catch (Throwable e) {
if (c instanceof javax.imageio.stream.ImageOutputStream)
return;
else
throw rethrow(e);
}
}
static public void internalFramePopupMenuItem(Container f, final String name, final Object action) {
internalFrameTitlePopupMenuItem(((JInternalFrame) f), name, action);
}
static public Runnable runnableThread(final Runnable r) {
return new Runnable() {
public void run() {
try {
startThread(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "startThread(r)";
}
};
}
static public void minFrameSize(Component c, int w, int h) {
minimalFrameSize(c, w, h);
}
static public Thread startThread(Object runnable) {
return startThread(defaultThreadName(), runnable);
}
static public Thread startThread(String name, Object runnable) {
runnable = wrapAsActivity(runnable);
return startThread(newThread(toRunnable(runnable), name));
}
static public Thread startThread(Thread t) {
_registerThread(t);
t.start();
return t;
}
static volatile public PersistableThrowable _handleException_lastException;
static public List _handleException_onException = synchroList(ll("printStackTrace2"));
static public void _handleException(Throwable e) {
_handleException_lastException = persistableThrowable(e);
Throwable e2 = innerException(e);
if (e2.getClass() == RuntimeException.class && eq(e2.getMessage(), "Thread cancelled.") || e2 instanceof InterruptedException)
return;
for (Object f : cloneList(_handleException_onException)) try {
callF(f, e);
} catch (Throwable e3) {
printStackTrace2(e3);
}
}
static public boolean dm_isMe(Object mod) {
return dm_getModule(mod) == dm_current_mandatory();
}
static public String getString(Map map, Object key) {
return map == null ? null : (String) map.get(key);
}
static public String getString(List l, int idx) {
return (String) get(l, idx);
}
static public String getString(Object o, Object key) {
if (o instanceof Map)
return getString((Map) o, key);
if (key instanceof String)
return (String) getOpt(o, (String) key);
throw fail("Not a string key: " + getClassName(key));
}
static public String getString(String key, Object o) {
return getString(o, (Object) key);
}
static public long now_virtualTime;
static public long now() {
return now_virtualTime != 0 ? now_virtualTime : System.currentTimeMillis();
}
static public Object dm_rcall(String method, Object moduleOrID, Object... args) {
return dm_call(moduleOrID, method, args);
}
static public long rcall_long(String method, Object o, Object... args) {
return toLong(rcall(method, o, args));
}
static public String lstr(Map map) {
return str(l(map));
}
static public String lstr(Collection c) {
return str(l(c));
}
static public String lstr(String s) {
return str(l(s));
}
static public List dm_activeDiscordTokens() {
return concatLists((List>) vmBus_queryAll("activeDiscordTokens"));
}
static public List extractPossibleDiscordTokens(String s) {
return regexpAll(discordTokenRegexp(), s);
}
static public String unnull(String s) {
return s == null ? "" : s;
}
static public Collection unnull(Collection l) {
return l == null ? emptyList() : l;
}
static public List unnull(List l) {
return l == null ? emptyList() : l;
}
static public Map unnull(Map l) {
return l == null ? emptyMap() : l;
}
static public Iterable unnull(Iterable i) {
return i == null ? emptyList() : i;
}
static public A[] unnull(A[] a) {
return a == null ? (A[]) new Object[0] : a;
}
static public BitSet unnull(BitSet b) {
return b == null ? new BitSet() : b;
}
static public Pt unnull(Pt p) {
return p == null ? new Pt() : p;
}
static public Pair unnull(Pair p) {
return p != null ? p : new Pair(null, null);
}
static public List concatLists(Collection ... lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List concatLists(Collection extends Collection > lists) {
List l = new ArrayList();
if (lists != null)
for (Collection list : lists) if (list != null)
l.addAll(list);
return l;
}
static public List vmBus_queryAll(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
List out = new ArrayList();
for (Object o : unnull(vm_busListeners_live())) addIfNotNull(out, pcallF(o, msg, arg));
for (Object o : unnull(vm_busListenersByMessage_live().get(msg))) addIfNotNull(out, pcallF(o, msg, arg));
return out;
}
static public String dm_showNewModuleWithParams(String moduleLibID, Object... params) {
String moduleID = dm_makeNewModuleWithParams(moduleLibID, params);
dm_showModule(moduleID);
return moduleID;
}
static public String dm_moduleLibID() {
return programID() + "/" + shortClassName(dm_current_mandatory());
}
static public String dm_moduleLibID(Object mod) {
if (mod == null)
return null;
mod = dm_getModule(mod);
if (hasSuperclassShortNamed(mod, "DynModule"))
return programID(mod) + "/" + shortClassName(mod);
return null;
}
static public String discordAt(long userID) {
return userID == 0 ? "unknown person" : "<@" + userID + ">";
}
static public void dm_watchField(String field, Runnable onChange) {
new Dyn_FieldWatcher(dm_current_mandatory(), field, onChange);
}
static public void dm_reloadModule(Object module) {
dm_reloadModuleInBackground(module);
}
static public void dm_reloadModule() {
dm_reloadModuleInBackground();
}
static public Object first(Object list) {
return first((Iterable) list);
}
static public A first(List list) {
return empty(list) ? null : list.get(0);
}
static public A first(A[] bla) {
return bla == null || bla.length == 0 ? null : bla[0];
}
static public A first(IterableIterator i) {
return first((Iterator ) i);
}
static public A first(Iterator i) {
return i == null || !i.hasNext() ? null : i.next();
}
static public A first(Iterable i) {
if (i == null)
return null;
Iterator it = i.iterator();
return it.hasNext() ? it.next() : null;
}
static public Character first(String s) {
return empty(s) ? null : s.charAt(0);
}
static public A first(Pair p) {
return p == null ? null : p.a;
}
static public double elapsedMinutes_timestamp(long time) {
return toMinutes(now() - time);
}
static public void containerAddFirst(final Container c, final Component... l) {
{
swing(new Runnable() {
public void run() {
try {
for (int i = 0; i < l(l); i++) c.add(l[i], i);
revalidate(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "for (int i = 0; i < l(l); i++)\r\n c.add(l[i], i);\r\n revalidate(c);";
}
});
}
}
static public JButton jThreadedButton(final String text, final Object action) {
return swing(new F0() {
public JButton get() {
try {
String text2 = dropPrefix("[disabled] ", text);
final JButton btn = new JButton(text2);
if (l(text2) < l(text))
btn.setEnabled(false);
btn.setToolTipText(btn.getText());
if (action != null)
btn.addActionListener(actionListenerInNewThread(action, btn));
return btn;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "S text2 = dropPrefix(\"[disabled] \", text);\r\n final JButton btn = new JButt...";
}
});
}
static public void dm_stringFieldDialog(final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
final JTextField tf = jtextfield(get(m, field));
showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() {
public void run() {
try {
m.setField(field, gtt(tf));
callF(optPar(__, "onSet"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.setField(field, gtt(tf));\r\n callF(optPar(__, \"onSet\"));";
}
});
}
static public void addToContainer(final Container a, final Component b) {
if (a != null && b != null) {
swing(new Runnable() {
public void run() {
try {
a.add(b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "a.add(b);";
}
});
}
}
static public JButton jPopDownButton_noText(final Object... menuParams) {
return toolTip("Additional commands", jPopDownButton("", menuParams));
}
static public void dm_exportStructureToTextFileDialog(DynModule mod) {
File defaultFile = javaxBackupDir("module-" + shortClassName(mod) + "-" + ymdMinusHms() + ".txt");
inputText("Text file to save data in (" + dm_moduleName(mod) + ")", f2s(defaultFile), new VF1() {
public void get(String path) {
try {
saveTextFileWithInfoBox(newFile(path), javaTokWordWrap(dm_freshModuleStructureWithoutError(mod)));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "saveTextFileWithInfoBox(newFile(path),\r\n javaTokWordWrap(dm_freshModul...";
}
});
}
static public void dm_importStructureFromTextFileDialog(DynModule mod) {
File f = showFileChooserWithDefaultDir("Module data to restore", javaxBackupDir());
if (fileExists(f)) {
infoBox("Replacing module with " + f2s(f));
dm_replaceModuleWithStructure(mod, loadTextFile(f));
}
}
static public A assertNotNull(A a) {
assertTrue(a != null);
return a;
}
static public A assertNotNull(String msg, A a) {
assertTrue(msg, a != null);
return a;
}
static public A setEnabled(A c, boolean enable) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
c.setEnabled(enable);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.setEnabled(enable);";
}
});
}
return c;
}
static public A setEnabled(boolean enable, A c) {
return setEnabled(c, enable);
}
static public void dm_reload() {
dm_reloadMe();
}
static public int hashCodeFor(Object a) {
return a == null ? 0 : a.hashCode();
}
static public JPanel jSection(Component c) {
return jSection("", c);
}
static public JPanel jSection(final String title, final Component c) {
return swing(new F0() {
public JPanel get() {
try {
Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);
border = BorderFactory.createTitledBorder(border, title);
JSection panel = new JSection(c);
panel.setBorder(border);
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Border border = BorderFactory.createBevelBorder(BevelBorder.LOWERED);\r\n bo...";
}
});
}
static public JPanel jSection(String title) {
return jSection(title, jpanel());
}
static public JScrollPane jscroll_copyBackground(Component c) {
return setScrollPaneBackground(getBackground(c), jscroll(c));
}
static public JFastLogView_noWrap jFastLogView_noWrap() {
return jFastLogView_noWrap("");
}
static public JFastLogView_noWrap jFastLogView_noWrap(String text) {
return withTypeWriterFont(swingNu(JFastLogView_noWrap.class, text));
}
static public String getPrintLog() {
return str(print_log);
}
static public A componentPopupMenuItem(A c, final String name, final Object action) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, name, action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, name, action);";
}
});
return c;
}
static public void componentPopupMenuItem(JComponent c, final JMenuItem menuItem) {
componentPopupMenu(c, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, menuItem);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, menuItem);";
}
});
}
static public void dm_clearModulePrintLog() {
clearStringBuffer_gen(dm_current_mandatory()._actualPrintLog());
}
static public A awtEvery(A component, long delay, Object r) {
swingEvery(component, delay, r);
return component;
}
static public A awtEvery(A component, long delay, long firstDelay, Object r) {
swingEvery(component, delay, firstDelay, r);
return component;
}
static public void awtEvery(RootPaneContainer frame, long delay, Object r) {
swingEvery(frame, delay, r);
}
static public A awtEvery(A component, double delaySeconds, Object r) {
return awtEvery(component, toMS(delaySeconds), r);
}
static public boolean scrollAllTheWayDown_bruteForce = true;
static public void scrollAllTheWayDown(final JComponent c) {
if (c != null) {
swing(new Runnable() {
public void run() {
try {
int h = c.getHeight() - 1;
if (scrollAllTheWayDown_bruteForce)
h = max(h, 100000);
c.scrollRectToVisible(new Rectangle(0, h, 1, 1));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "int h = c.getHeight()-1;\r\n if (scrollAllTheWayDown_bruteForce) h = max(h, ...";
}
});
}
}
static public void awtLater(int delay, final Object r) {
swingLater(delay, r);
}
static public void awtLater(Object r) {
swingLater(r);
}
static public void awtLater(JComponent component, int delay, Object r) {
installTimer(component, r, delay, delay, false);
}
static public void awtLater(JFrame frame, int delay, Object r) {
awtLater(frame.getRootPane(), delay, r);
}
static public StringBuffer liveLocalPrintLog_realMC(Object o) {
Object realMC = getMainClass(o);
if (realMC != mc())
return (StringBuffer) getOpt(realMC, "local_log");
return liveLocalPrintLog();
}
static public String str(Object o) {
return o == null ? "null" : o.toString();
}
static public String str(char[] c) {
return new String(c);
}
static public Dimension getPreferredSize(final Component c) {
return c == null ? null : swing(new F0() {
public Dimension get() {
try {
return c.getPreferredSize();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getPreferredSize();";
}
});
}
static public int getWidth(Component c) {
return c == null ? 0 : (int) swingCall(c, "getWidth");
}
static public int getHeight(Component c) {
return c == null ? 0 : (int) swingCall(c, "getHeight");
}
static public Color getBackground(final Component c) {
return c == null ? null : swing(new F0() {
public Color get() {
try {
return c.getBackground();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getBackground();";
}
});
}
static public FontMetrics componentFontMetrics(JComponent c) {
Font font = getFont(c);
return font == null ? null : swing(new F0() {
public FontMetrics get() {
try {
return c.getFontMetrics(font);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getFontMetrics(font);";
}
});
}
static public int max(int a, int b) {
return Math.max(a, b);
}
static public int max(int a, int b, int c) {
return max(max(a, b), c);
}
static public long max(int a, long b) {
return Math.max((long) a, b);
}
static public long max(long a, long b) {
return Math.max(a, b);
}
static public double max(int a, double b) {
return Math.max((double) a, b);
}
static public float max(float a, float b) {
return Math.max(a, b);
}
static public double max(double a, double b) {
return Math.max(a, b);
}
static public int max(Collection c) {
int x = Integer.MIN_VALUE;
for (int i : c) x = max(x, i);
return x;
}
static public double max(double[] c) {
if (c.length == 0)
return Double.MIN_VALUE;
double x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public float max(float[] c) {
if (c.length == 0)
return Float.MAX_VALUE;
float x = c[0];
for (int i = 1; i < c.length; i++) x = Math.max(x, c[i]);
return x;
}
static public byte max(byte[] c) {
byte x = -128;
for (byte d : c) if (d > x)
x = d;
return x;
}
static public short max(short[] c) {
short x = -0x8000;
for (short d : c) if (d > x)
x = d;
return x;
}
static public int max(int[] c) {
int x = Integer.MIN_VALUE;
for (int d : c) if (d > x)
x = d;
return x;
}
static public int min(int a, int b) {
return Math.min(a, b);
}
static public long min(long a, long b) {
return Math.min(a, b);
}
static public float min(float a, float b) {
return Math.min(a, b);
}
static public float min(float a, float b, float c) {
return min(min(a, b), c);
}
static public double min(double a, double b) {
return Math.min(a, b);
}
static public double min(double[] c) {
double x = Double.MAX_VALUE;
for (double d : c) x = Math.min(x, d);
return x;
}
static public float min(float[] c) {
float x = Float.MAX_VALUE;
for (float d : c) x = Math.min(x, d);
return x;
}
static public byte min(byte[] c) {
byte x = 127;
for (byte d : c) if (d < x)
x = d;
return x;
}
static public short min(short[] c) {
short x = 0x7FFF;
for (short d : c) if (d < x)
x = d;
return x;
}
static public int min(int[] c) {
int x = Integer.MAX_VALUE;
for (int d : c) if (d < x)
x = d;
return x;
}
static public int idiv_ceil(int a, int b) {
return (a + b - 1) / b;
}
static public int idiv_ceil(long a, long b) {
return toInt_checked((a + b - 1) / b);
}
static public boolean setText_opt = true;
static public A setText(A c, Object text) {
setText((JComponent) c, text);
return c;
}
static public A setText(final A c, Object text) {
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
c.getEditor().setItem(s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "c.getEditor().setItem(s);";
}
});
}
return c;
}
static public void setText(JLabel c, Object text) {
setText((JComponent) c, text);
}
static public JButton setText(JButton c, Object text) {
setText((JComponent) c, jlabel_textAsHTML_center_ifNeeded(strUnnull(text)));
return c;
}
static public A setText(final A c, Object text) {
if (c == null)
return null;
final String s = strUnnull(text);
{
swing(new Runnable() {
public void run() {
try {
if (!setText_opt || neq(callOpt(c, "getText"), s))
call(c, "setText", s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!setText_opt || neq(callOpt(c, \"getText\"), s))\r\n call(c, \"setText\", s);";
}
});
}
return c;
}
static public List asSyncList(Iterable l) {
return asSynchroList(l);
}
static public A _revalidate(A c) {
return revalidate(c);
}
static public void _revalidate(JFrame f) {
revalidate(f);
}
static public void _revalidate(JInternalFrame f) {
revalidate(f);
}
static public boolean endsWithNewLine(String s) {
return endsWith(s, "\n");
}
static public String getText(final AbstractButton c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JTextComponent c) {
return c == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return c.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getText();";
}
});
}
static public String getText(final JLabel l) {
return l == null ? "" : (String) swingAndWait(new F0() {
public Object get() {
try {
return l.getText();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret l.getText();";
}
});
}
static public String getText(final JComboBox cb) {
if (cb == null)
return null;
if (isEditableComboBox(cb))
return unnull((String) cb.getEditor().getItem());
else
return str(cb.getSelectedItem());
}
static public String lines_rtrimIf(boolean rtrim, List lines) {
return rtrim ? lines_rtrim(lines) : lines(lines);
}
static public ArrayList cloneList(Iterable l) {
return l instanceof Collection ? cloneList((Collection) l) : asList(l);
}
static public ArrayList cloneList(Collection l) {
if (l == null)
return new ArrayList();
synchronized (collectionMutex(l)) {
return new ArrayList (l);
}
}
static public String copyTextToClipboard(Object _text) {
String text = str(_text);
StringSelection selection = new StringSelection(text);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(selection, selection);
vmBus_send("newClipboardContents", text);
return text;
}
static public Map newWeakHashMap() {
return _registerWeakMap(synchroMap(new WeakHashMap()));
}
static public Set synchroHashSet() {
return Collections.synchronizedSet(new HashSet ());
}
static public Map synchroHashMap() {
return Collections.synchronizedMap(new HashMap());
}
static public Flag dm_initErrorHandling_flag = new Flag();
static public void dm_initErrorHandling() {
raiseFlagAndDo(dm_initErrorHandling_flag, new Runnable() {
public void run() {
try {
_handleException_addHandler("dm_initErrorHandling_handler");
assertNull(_onRegisterThread);
_onRegisterThread = new VF1() {
public void get(Thread t) {
try {
DynModule m = dm_currentModule();
if (m == null)
printStackTrace("New thread made outside of a module");
else
m.ownTimer(t);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "DynModule m = dm_currentModule();\r\n if (m == null) printStackTrace(\"New ...";
}
};
_threadInfo_makers.add(new VF1() {
public void get(Map map) {
try {
mapPut(map, "dm_currentModule_value", dm_currentModule());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "mapPut(map, 'dm_currentModule_value, dm_currentModule())";
}
});
_threadInheritInfo_retrievers.add(new VF1() {
public void get(Map map) {
try {
Object mod = map.get("dm_currentModule_value");
if (mod instanceof DynModule)
dm_currentModule_value.set(new WeakReference((DynModule) mod));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O mod = map.get('dm_currentModule_value);\r\n if (mod instanceof DynModule...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "_handleException_addHandler(f dm_initErrorHandling_handler);\r\n \r\n asser...";
}
});
}
static public void dm_initErrorHandling_handler(Throwable e) {
DynModule m = dm_currentModule();
if (m == null)
print("Weird: Error outside of module");
else
m.setField("_error", persistableThrowable(e));
}
static public void setMainDesktopPane(JDesktopPane desktop) {
mainDesktopPane_value = desktop;
}
static public A getCreatorOpt(String field) {
return (A) getOpt(creator(), field);
}
static public boolean isTrue(Object o) {
if (o instanceof Boolean)
return ((Boolean) o).booleanValue();
if (o == null)
return false;
if (o instanceof ThreadLocal)
return isTrue(((ThreadLocal) o).get());
throw fail(getClassName(o));
}
static public Object getOpt(Object o, String field) {
return getOpt_cached(o, field);
}
static public Object getOpt(String field, Object o) {
return getOpt_cached(o, field);
}
static public Object getOpt_raw(Object o, String field) {
try {
Field f = getOpt_findField(o.getClass(), field);
if (f == null)
return null;
makeAccessible(f);
return f.get(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object getOpt(Class c, String field) {
try {
if (c == null)
return null;
Field f = getOpt_findStaticField(c, field);
if (f == null)
return null;
makeAccessible(f);
return f.get(null);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Field getOpt_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public A possiblyInternalFrameTitle(A c, String title) {
JInternalFrame f = getInternalFrame(c);
if (f != null)
internalFrameTitle(f, title);
else
frameTitle(getFrame(c), title);
return c;
}
static public String possiblyInternalFrameTitle(Component c) {
JInternalFrame f = getInternalFrame(c);
return f != null ? internalFrameTitle(f) : frameTitle(getFrame(c));
}
static public void vmBus_send(String msg, Object... args) {
Object arg = vmBus_wrapArgs(args);
pcallFAll(vm_busListeners_live(), msg, arg);
pcallFAll(vm_busListenersByMessage_live().get(msg), msg, arg);
}
static public void vmBus_send(String msg) {
vmBus_send(msg, (Object) null);
}
static public void ownResource(AutoCloseable c) {
_registerAutoCloseable(c);
}
static public List getAndClearList(Collection l) {
if (l == null)
return emptyList();
synchronized (collectionMutex(l)) {
List out = cloneList(l);
l.clear();
return out;
}
}
static public Map getAndClearMap(Map map) {
if (map == null)
return emptyMap();
synchronized (collectionMutex(map)) {
Map out = cloneMap(map);
map.clear();
return out;
}
}
static public Set keys(Map map) {
return map == null ? new HashSet() : map.keySet();
}
static public Set keys(Object map) {
return keys((Map) map);
}
static public Object pcallFInRealOrMyMC(final Object realm, final Object f, final Object... args) {
try {
return callFInRealOrMyMC(realm, f, args);
} catch (Throwable __e) {
_handleException(__e);
}
return null;
}
static public A pcallFInRealOrMyMC(Object realm, F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallFInRealOrMyMC(Object realm, F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public Object callOpt(Object o) {
return callF(o);
}
static public A callOpt(Object o, String method, Object... args) {
return (A) callOpt_withVarargs(o, method, args);
}
static public A set(A o, String field, Object value) {
if (o == null)
return null;
if (o instanceof Class)
set((Class) o, field, value);
else
try {
Field f = set_findField(o.getClass(), field);
makeAccessible(f);
smartSet(f, o, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
return o;
}
static public void set(Class c, String field, Object value) {
if (c == null)
return;
try {
Field f = set_findStaticField(c, field);
makeAccessible(f);
smartSet(f, null, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public Field set_findStaticField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field) && (f.getModifiers() & java.lang.reflect.Modifier.STATIC) != 0)
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Static field '" + field + "' not found in " + c.getName());
}
static public Field set_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
throw new RuntimeException("Field '" + field + "' not found in " + c.getName());
}
static public boolean isFalse(Object o) {
return eq(false, o);
}
static public B mapGet(Map map, A a) {
return map == null || a == null ? null : map.get(a);
}
static public B mapGet(A a, Map map) {
return map == null || a == null ? null : map.get(a);
}
static public Rect dm_getBounds(Object module) {
return shallowCloneToClass(Rect.class, call(dm_getStem(module), "getFrameRect"));
}
static public Rect dm_getBounds() {
return dm_getBounds(dm_current_generic());
}
static public boolean hasMethod_onTypes(Object o, String method, Class... argTypes) {
return findMethod_precise_onTypes(o, method, argTypes) != null;
}
static public void dm_onTopInput_q(final VF1 r) {
final DynModule m = dm_current_mandatory();
dm_onTopInput(new VF1() {
public void get(final String s) {
try {
m.q().add(new Runnable() {
public void run() {
try {
callF(r, s);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r, s);";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "switch to m.q();\r\n callF(r, s);";
}
});
}
static public Object call(Object o) {
return callF(o);
}
static public Object call(Object o, String method, String[] arg) {
return call(o, method, new Object[] { arg });
}
static public Object call(Object o, String method, Object... args) {
return call_withVarargs(o, method, args);
}
static public WeakReference creator_class;
static public Object creator() {
return creator_class == null ? null : creator_class.get();
}
static public AutoCloseable tempSetThreadLocal(final ThreadLocal tl, A a) {
if (tl == null)
return null;
final A prev = setThreadLocal(tl, a);
return new AutoCloseable() {
public String toString() {
return "tl.set(prev);";
}
public void close() throws Exception {
tl.set(prev);
}
};
}
static public Class getMainClass() {
return mc();
}
static public Class getMainClass(Object o) {
try {
if (o == null)
return null;
if (o instanceof Class && eq(((Class) o).getName(), "x30"))
return (Class) o;
return (o instanceof Class ? (Class) o : o.getClass()).getClassLoader().loadClass("main");
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable combineAutoCloseables(final AutoCloseable a, final AutoCloseable b) {
return a == null ? b : b == null ? a : new AutoCloseable() {
public String toString() {
return "a.close(); b.close();";
}
public void close() throws Exception {
a.close();
b.close();
}
};
}
static public AutoCloseable combineAutoCloseables(AutoCloseable a, AutoCloseable b, AutoCloseable c, AutoCloseable... more) {
return combineAutoCloseables(concatLists(ll(a, b, c), asList(more)));
}
static public AutoCloseable combineAutoCloseables(Iterable l) {
return foldl(new F2() {
public AutoCloseable get(AutoCloseable a, AutoCloseable b) {
try {
return combineAutoCloseables(a, b);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "combineAutoCloseables(a,b)";
}
}, null, l);
}
static public AutoCloseable tempInterceptPrintIfNotIntercepted(F1 f) {
return print_byThread().get() == null ? tempInterceptPrint(f) : null;
}
static public Class mc() {
return dtb.class;
}
static public AutoCloseable tempSetTL(ThreadLocal tl, A a) {
return tempSetThreadLocal(tl, a);
}
static public ThreadLocal realMC_tl_tl = new ThreadLocal();
static public ThreadLocal realMC_tl() {
return realMC_tl_tl;
}
static public Map> callF_cache = newDangerousWeakHashMap();
static public A callF(F0 f) {
return f == null ? null : f.get();
}
static public B callF(F1 f, A a) {
return f == null ? null : f.get(a);
}
static public A callF(IF0 f) {
return f == null ? null : f.get();
}
static public B callF(IF1 f, A a) {
return f == null ? null : f.get(a);
}
static public C callF(F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public C callF(IF2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callF(VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callF(Object f, Object... args) {
try {
if (f instanceof String)
return callMC((String) f, args);
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
}
if (f == null)
return null;
Class c = f.getClass();
ArrayList methods;
synchronized (callF_cache) {
methods = callF_cache.get(c);
if (methods == null)
methods = callF_makeCache(c);
}
int n = l(methods);
if (n == 0) {
throw fail("No get method in " + getClassName(c));
}
if (n == 1)
return invokeMethod(methods.get(0), f, args);
for (int i = 0; i < n; i++) {
Method m = methods.get(i);
if (call_checkArgs(m, args, false))
return invokeMethod(m, f, args);
}
throw fail("No matching get method in " + getClassName(c));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ArrayList callF_makeCache(Class c) {
ArrayList l = new ArrayList();
Class _c = c;
do {
for (Method m : _c.getDeclaredMethods()) if (m.getName().equals("get")) {
makeAccessible(m);
l.add(m);
}
if (!l.isEmpty())
break;
_c = _c.getSuperclass();
} while (_c != null);
callF_cache.put(c, l);
return l;
}
static public String fixNewLines(String s) {
int i = indexOf(s, '\r');
if (i < 0)
return s;
int l = s.length();
StringBuilder out = new StringBuilder(l);
out.append(s, 0, i);
for (; i < l; i++) {
char c = s.charAt(i);
if (c != '\r')
out.append(c);
else {
out.append('\n');
if (i + 1 < l && s.charAt(i + 1) == '\n')
++i;
}
}
return out.toString();
}
static public void print_append(Appendable buf, String s, int max) {
try {
synchronized (buf) {
buf.append(s);
if (buf instanceof StringBuffer)
rotateStringBuffer(((StringBuffer) buf), max);
else if (buf instanceof StringBuilder)
rotateStringBuilder(((StringBuilder) buf), max);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public AutoCloseable tempLock(final Lock lock) {
if (lock == null)
return null;
lock(lock);
return new AutoCloseable() {
public String toString() {
return "unlock(lock);";
}
public void close() throws Exception {
unlock(lock);
}
};
}
static public PersistableThrowable persistableThrowable(Throwable e) {
return e == null ? null : new PersistableThrowable(e);
}
static public boolean addIfNotThere(Collection c, A a) {
return setAdd(c, a);
}
static public A onChange(A spinner, Object r) {
{
swing(new Runnable() {
public void run() {
try {
spinner.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "spinner.addChangeListener(changeListener(r));";
}
});
}
return spinner;
}
static public A onChange(A b, Object r) {
{
swing(new Runnable() {
public void run() {
try {
b.addItemListener(itemListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "b.addItemListener(itemListener(r));";
}
});
}
return b;
}
static public void onChange(JTextComponent tc, Object r) {
onUpdate(tc, r);
}
static public A onChange(A slider, final Object r) {
{
swing(new Runnable() {
public void run() {
try {
slider.addChangeListener(changeListener(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "slider.addChangeListener(changeListener(r));";
}
});
}
return slider;
}
static public JComboBox onChange(Object r, JComboBox cb) {
return onChange(cb, r);
}
static public JComboBox onChange(JComboBox cb, final Object r) {
if (isEditableComboBox(cb))
onChange(textFieldFromComboBox(cb), r);
else
onSelectedItem(cb, new VF1() {
public void get(String s) {
try {
callF(r);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(r)";
}
});
return cb;
}
static public void onUpdateAndNow(JComponent c, final Object r) {
onUpdate(c, r);
callF(r);
}
static public void onUpdateAndNow(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
callF(r);
}
static public void onUpdate(JComponent c, final Object r) {
if (c instanceof JTextComponent)
((JTextComponent) c).getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
call(r);
}
public void removeUpdate(DocumentEvent e) {
call(r);
}
public void changedUpdate(DocumentEvent e) {
call(r);
}
});
else if (c instanceof ItemSelectable)
((ItemSelectable) c).addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
call(r);
}
});
else
print("Warning: onUpdate doesn't know " + getClassName(c));
}
static public void onUpdate(List extends JComponent> l, Object r) {
for (JComponent c : l) onUpdate(c, r);
}
static public void zeroAllFieldsOfTypeExcept(Object o, Class type, String... exceptions) {
zeroAllFieldsOfTypeExcept(o, type, asSet(exceptions));
}
static public void zeroAllFieldsOfTypeExcept(Object o, Class type, Collection exceptions) {
Set set = asSet(exceptions);
for (String field : allFields(o)) if (!set.contains(field) && instanceOf(getOpt(o, field), type))
set(o, field, null);
}
static public void internalFramePopupMenuFromActions_threaded(Container f, List actions) {
if (!(f instanceof JInternalFrame))
return;
for (final AbstractAction a : unnull(actions)) if (a != null)
internalFramePopupMenuItem(((JInternalFrame) f), str(a.getValue(Action.NAME)), runnableThread(new Runnable() {
public void run() {
try {
callAction(a);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callAction(a)";
}
}));
}
static public LinkedHashSet asLinkedHashSet(A[] array) {
LinkedHashSet set = new LinkedHashSet();
for (A o : array) if (o != null)
set.add(o);
return set;
}
static public LinkedHashSet asLinkedHashSet(Collection l) {
if (l instanceof LinkedHashSet)
return (LinkedHashSet) l;
LinkedHashSet set = new LinkedHashSet();
for (A o : l) if (o != null)
set.add(o);
return set;
}
static public List splitAtSpace(String s) {
return empty(s) ? emptyList() : asList(s.split("\\s+"));
}
static public Set allFields(Object o) {
TreeSet fields = new TreeSet();
Class _c = _getClass(o);
do {
for (Field f : _c.getDeclaredFields()) fields.add(f.getName());
_c = _c.getSuperclass();
} while (_c != null);
return fields;
}
static public boolean startsWith(String a, String b) {
return a != null && a.startsWith(b);
}
static public boolean startsWith(String a, char c) {
return nemptyString(a) && a.charAt(0) == c;
}
static public boolean startsWith(String a, String b, Matches m) {
if (!startsWith(a, b))
return false;
m.m = new String[] { substring(a, strL(b)) };
return true;
}
static public boolean startsWith(List a, List b) {
if (a == null || listL(b) > listL(a))
return false;
for (int i = 0; i < listL(b); i++) if (neq(a.get(i), b.get(i)))
return false;
return true;
}
static public Class fieldType(Object o, String field) {
Field f = getField(o, field);
return f == null ? null : f.getType();
}
static public void dm_boolFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFrameTitlePopupMenu(((JInternalFrame) frame), new VF1() {
public void get(JPopupMenu menu) {
try {
menu.add(jCheckBoxMenuItem(humanized, (boolean) _get(m, field), new VF1() {
public void get(Boolean b) {
try {
m.setField(field, b);
callF(optPar(__, "onSet"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.setField(field, b);\r\n callF(optPar(_, 'onSet));";
}
}));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "menu.add(jCheckBoxMenuItem(humanized, (bool) _get(m, field), voidfunc(bool b)...";
}
});
}
static public void dm_intFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(get(m, field));
showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() {
public void run() {
try {
m.setField(field, parseInt(gtt(tf)));
callF(optPar(__, "onSet"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.setField(field, parseInt(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri...";
}
});
}
static public void dm_doubleFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
final String humanized = humanizeFormLabel(field);
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(get(m, field));
showFormTitled(or2(stringOptPar(__, "formTitle"), "Set " + humanized), humanized + ":", tf, new Runnable() {
public void run() {
try {
m.setField(field, parseDouble(gtt(tf)));
callF(optPar(__, "onSet"));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "m.setField(field, parseDouble(gtt(tf)));\r\n callF(optPar(__, \"onSet\"));";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jtextfield(get(m, field));\r\n showFormTitled(or2(stri...";
}
});
}
static public void dm_stringFieldMenuItem(Container frame, final String field, final Object... __) {
final DynModule m = dm_current_mandatory();
internalFramePopupMenuItem(((JInternalFrame) frame), humanizeFormLabel(field) + "...", new Runnable() {
public void run() {
try {
AutoCloseable __0 = m.enter();
try {
dm_stringFieldDialog(field, __);
} finally {
_close(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __0 = m.enter(); try {\r\n dm_stringFieldDialog(field, __);\r\n ...";
}
});
}
static public ReliableSingleThread dm_rst(Runnable r) {
return dm_rst(dm_current_mandatory(), r);
}
static public ReliableSingleThread dm_rst(DynModule mod, Runnable r) {
return dm_rst(mod, new ReliableSingleThread(r));
}
static public ReliableSingleThread dm_rst(DynModule mod, ReliableSingleThread rst) {
rst.enter = dm_rEnter(mod);
return rst;
}
static public Q dm_startQ() {
Q q = startQ();
q.rst.enter = dm_rEnter(dm_current_mandatory());
dm_ownResource(q);
return q;
}
static public JComponent dm_noVisualisation() {
return setToolTip("Module has no visualization", jimage("#1101480"));
}
static public String snippetTitle(String id) {
return getSnippetTitle(id);
}
static public String snippetTitle(long id) {
return getSnippetTitle(id);
}
static public Class mainClass() {
return getMainClass();
}
static public Class mainClass(Object o) {
return getMainClass(o);
}
static public Map mapMinus(Map map, Object... keys) {
if (empty(keys))
return map;
Map m2 = cloneMap(map);
for (Object key : keys) m2.remove(key);
return m2;
}
static public Map mapPlus(Map m, Object... data) {
m = cloneMap(m);
litmap_impl(m, data);
return m;
}
static public Set _registerTimer_list = newWeakHashSet();
static public void _registerTimer_original(java.util.Timer timer) {
_registerTimer_list.add(timer);
}
static public void cleanMeUp__registerTimer() {
cancelTimers(getAndClearList(_registerTimer_list));
}
static public List synchroLinkedList() {
return Collections.synchronizedList(new LinkedList ());
}
static public Class _run(String progID, String... args) {
Class main = hotwire(progID);
callMain(main, args);
return main;
}
static public void add(BitSet bs, int i) {
bs.set(i);
}
static public boolean add(Collection c, A a) {
return c != null && c.add(a);
}
static public void add(Container c, Component x) {
addToContainer(c, x);
}
static public Runnable toRunnable(final Object o) {
if (o instanceof Runnable)
return (Runnable) o;
return new Runnable() {
public void run() {
try {
callF(o);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "callF(o)";
}
};
}
static volatile public boolean licensed_yes = true;
static public boolean licensed() {
if (!licensed_yes)
return false;
ping_okInCleanUp();
return true;
}
static public void licensed_off() {
licensed_yes = false;
}
static public A syncPopFirst(List l) {
if (empty(l))
return null;
synchronized (l) {
A a = first(l);
l.remove(0);
return a;
}
}
static volatile public boolean sleep_noSleep = false;
static public void sleep(long ms) {
ping();
if (ms < 0)
return;
if (isAWTThread() && ms > 100)
throw fail("Should not sleep on AWT thread");
try {
Thread.sleep(ms);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static public void sleep() {
try {
if (sleep_noSleep)
throw fail("nosleep");
print("Sleeping.");
sleepQuietly();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object pcallF(Object f, Object... args) {
return pcallFunction(f, args);
}
static public A pcallF(F0 f) {
try {
return f == null ? null : f.get();
} catch (Throwable __e) {
return null;
}
}
static public B pcallF(F1 f, A a) {
try {
return f == null ? null : f.get(a);
} catch (Throwable __e) {
return null;
}
}
static public void pcallF(VF1 f, A a) {
try {
if (f != null)
f.get(a);
} catch (Throwable __e) {
_handleException(__e);
}
}
static public void cancelAndInterruptThread(Thread t) {
if (t == null)
return;
cancelThread(t);
t.interrupt();
}
static public String getClassName(Object o) {
return o == null ? "null" : o instanceof Class ? ((Class) o).getName() : o.getClass().getName();
}
static public String getStackTrace(Throwable throwable) {
lastException(throwable);
return getStackTrace_noRecord(throwable);
}
static public String getStackTrace_noRecord(Throwable throwable) {
StringWriter writer = new StringWriter();
throwable.printStackTrace(new PrintWriter(writer));
return hideCredentials(writer.toString());
}
static public String getStackTrace() {
return getStackTrace_noRecord(new Throwable());
}
static public ArrayList litlist(A... a) {
ArrayList l = new ArrayList(a.length);
for (A x : a) l.add(x);
return l;
}
static public Throwable printStackTrace2(Throwable e) {
print(getStackTrace2(e));
return e;
}
static public void printStackTrace2() {
printStackTrace2(new Throwable());
}
static public void printStackTrace2(String msg) {
printStackTrace2(new Throwable(msg));
}
static public Map _registerThread_threads;
static public Object _onRegisterThread;
static public Thread _registerThread(Thread t) {
if (_registerThread_threads == null)
_registerThread_threads = newWeakHashMap();
_registerThread_threads.put(t, true);
vm_generalWeakSubMap("thread2mc").put(t, weakRef(mc()));
callF(_onRegisterThread, t);
return t;
}
static public void _registerThread() {
_registerThread(Thread.currentThread());
}
static public List> _threadInheritInfo_retrievers = synchroList();
static public void _threadInheritInfo(Object info) {
if (info == null)
return;
pcallFAll(_threadInheritInfo_retrievers, (Map) info);
}
static public List> _threadInfo_makers = synchroList();
static public Object _threadInfo() {
if (empty(_threadInfo_makers))
return null;
HashMap map = new HashMap();
pcallFAll(_threadInfo_makers, map);
return map;
}
static public Object _onAWTEnter_f;
static public AutoCloseable _onAWTEnter() {
return (AutoCloseable) callF(_onAWTEnter_f);
}
static public JDesktopPane mainDesktopPane_value;
static public JDesktopPane mainDesktopPane() {
return mainDesktopPane_value;
}
static public InheritableThreadLocal dm_currentModule_value = new InheritableThreadLocal();
static public Object dm_current_generic() {
return getWeakRef(dm_currentModule_value.get());
}
static public void cleanMeUp_dm_current_generic() {
dm_currentModule_value = new InheritableThreadLocal();
}
static public void interruptThread(Thread t) {
if (t == null)
return;
t.interrupt();
URLConnection c = (URLConnection) (vm_generalSubMap("URLConnection per thread").get(t));
if (c != null) {
try {
print("Closing URLConnection of interrupted thread.");
call(c, "disconnect");
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public void cancelTimer(javax.swing.Timer timer) {
if (timer != null)
timer.stop();
}
static public void cancelTimer(java.util.Timer timer) {
if (timer != null)
timer.cancel();
}
static public void cancelTimer(Object o) {
if (o instanceof java.util.Timer)
cancelTimer((java.util.Timer) o);
else if (o instanceof javax.swing.Timer)
cancelTimer((javax.swing.Timer) o);
else if (o instanceof AutoCloseable) {
try {
((AutoCloseable) o).close();
} catch (Throwable __e) {
_handleException(__e);
}
}
}
static public Object nuObject(String className, Object... args) {
try {
return nuObject(classForName(className), args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A nuObject(Class c, Object... args) {
try {
if (args.length == 0)
return nuObjectWithoutArguments(c);
Constructor m = nuObject_findConstructor(c, args);
makeAccessible(m);
return (A) m.newInstance(args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Constructor nuObject_findConstructor(Class c, Object... args) {
for (Constructor m : c.getDeclaredConstructors()) {
if (!nuObject_checkArgs(m.getParameterTypes(), args, false))
continue;
return m;
}
throw fail("Constructor " + c.getName() + getClasses(args) + " not found" + (args.length == 0 && (c.getModifiers() & java.lang.reflect.Modifier.STATIC) == 0 ? " - hint: it's a non-static class!" : ""));
}
static public boolean nuObject_checkArgs(Class[] types, Object[] args, boolean debug) {
if (types.length != args.length) {
if (debug)
System.out.println("Bad parameter length: " + args.length + " vs " + types.length);
return false;
}
for (int i = 0; i < types.length; i++) if (!(args[i] == null || isInstanceX(types[i], args[i]))) {
if (debug)
System.out.println("Bad parameter " + i + ": " + args[i] + " vs " + types[i]);
return false;
}
return true;
}
static public A setAll(A o, Map fields) {
if (fields == null)
return o;
for (String field : keys(fields)) set(o, field, fields.get(field));
return o;
}
static public A setAll(A o, Object... values) {
failIfOddCount(values);
for (int i = 0; i + 1 < l(values); i += 2) {
String field = (String) values[i];
Object value = values[i + 1];
set(o, field, value);
}
return o;
}
static public Object getOptMC(String field) {
return getOpt(mc(), field);
}
static public DynModule dm_current_mandatory() {
return assertNotNull("No module set!", dm_currentModule());
}
static public AutoCloseable dm_vmBus_onMessage(final String msg, final VF1 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, final VF2 onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public AutoCloseable dm_vmBus_onMessage(String msg, Runnable onMessage) {
return dm_ownResource(vmBus_onMessage(msg, onMessage));
}
static public void ping_okInCleanUp() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
}
static public Object getThreadLocal(Object o, String name) {
ThreadLocal t = (ThreadLocal) (getOpt(o, name));
return t != null ? t.get() : null;
}
static public A getThreadLocal(ThreadLocal tl) {
return tl == null ? null : tl.get();
}
static public A getThreadLocal(ThreadLocal tl, A defaultValue) {
return or(getThreadLocal(tl), defaultValue);
}
static public ThreadLocal print_byThread_dontCreate() {
return print_byThread;
}
static public void _handleError(Error e) {
call(javax(), "_handleError", e);
}
static public RuntimeException fail() {
throw new RuntimeException("fail");
}
static public RuntimeException fail(Throwable e) {
throw asRuntimeException(e);
}
static public RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static public RuntimeException fail(String msg) {
throw new RuntimeException(msg == null ? "" : msg);
}
static public RuntimeException fail(String msg, Throwable innerException) {
throw new RuntimeException(msg, innerException);
}
static public String getType(Object o) {
return getClassName(o);
}
static public long getFileSize(String path) {
return path == null ? 0 : new File(path).length();
}
static public long getFileSize(File f) {
return f == null ? 0 : f.length();
}
static public boolean swic(String a, String b) {
return startsWithIgnoreCase(a, b);
}
static public boolean swic(String a, String b, Matches m) {
if (!swic(a, b))
return false;
m.m = new String[] { substring(a, l(b)) };
return true;
}
static public List dropPunctuation3_keep = ll("*", "<", ">");
static public Map dropPunctuation3_cache = defaultSizeMRUCache();
static public List dropPunctuation3(List tok) {
tok = new ArrayList(tok);
for (int i = 1; i < tok.size(); i += 2) {
String t = tok.get(i);
if (t.length() == 1 && !Character.isLetter(t.charAt(0)) && !Character.isDigit(t.charAt(0)) && !dropPunctuation3_keep.contains(t)) {
tok.set(i - 1, tok.get(i - 1) + tok.get(i + 1));
tok.remove(i);
tok.remove(i);
i -= 2;
}
}
return tok;
}
static public String dropPunctuation3(String s) {
return getOrCreate_f0(dropPunctuation3_cache, s, () -> join(dropPunctuation3(javaTokNoQuotes(s))));
}
static public boolean agiBlue_validPageName(String s) {
s = trim(s);
return nempty(s) && !containsNewLine(s);
}
static public String agiBlue_lookupInSlice_pcall(String sliceID, String q, String... keys) {
try {
return agiBlue_lookupInSlice(sliceID, q, keys);
} catch (Throwable __e) {
return null;
}
}
static public String agiBlue_postInSlice_pcall(String slice, String a, String b, String c) {
try {
return agiBlue_postInSlice(slice, a, b, c);
} catch (Throwable __e) {
return null;
}
}
static volatile public boolean ping_pauseAll = false;
static public int ping_sleep = 100;
static volatile public boolean ping_anyActions = false;
static public Map ping_actions = newWeakHashMap();
static public ThreadLocal ping_isCleanUpThread = new ThreadLocal();
static public boolean ping() {
if (ping_pauseAll || ping_anyActions)
ping_impl(true);
return true;
}
static public boolean ping_impl(boolean okInCleanUp) {
try {
if (ping_pauseAll && !isAWTThread()) {
do Thread.sleep(ping_sleep); while (ping_pauseAll);
return true;
}
if (ping_anyActions) {
if (!okInCleanUp && !isTrue(ping_isCleanUpThread.get()))
failIfUnlicensed();
Object action = null;
synchronized (ping_actions) {
if (!ping_actions.isEmpty()) {
action = ping_actions.get(currentThread());
if (action instanceof Runnable)
ping_actions.remove(currentThread());
if (ping_actions.isEmpty())
ping_anyActions = false;
}
}
if (action instanceof Runnable)
((Runnable) action).run();
else if (eq(action, "cancelled"))
throw fail("Thread cancelled.");
}
return false;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public A printStackTrace(A e) {
print(getStackTrace(e));
return e;
}
static public void printStackTrace() {
printStackTrace(new Throwable());
}
static public void printStackTrace(String msg) {
printStackTrace(new Throwable(msg));
}
static public void printStackTrace(String msg, Throwable e) {
printStackTrace(new Throwable(msg, e));
}
static public void lockOrFail(Lock lock, long timeout) {
try {
ping();
if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS)) {
String s = "Couldn't acquire lock after " + timeout + " ms.";
if (lock instanceof ReentrantLock) {
ReentrantLock l = (ReentrantLock) lock;
s += " Hold count: " + l.getHoldCount() + ", owner: " + call(l, "getOwner");
}
throw fail(s);
}
ping();
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public ReentrantLock fairLock() {
return new ReentrantLock(true);
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0)
throw fail("0 is not a snippet ID");
return id;
}
static public String programID;
static public String getProgramID() {
return nempty(programID) ? formatSnippetIDOpt(programID) : "?";
}
static public String getProgramID(Class c) {
String id = (String) getOpt(c, "programID");
if (nempty(id))
return formatSnippetID(id);
return "?";
}
static public String getProgramID(Object o) {
return getProgramID(getMainClass(o));
}
static public String substring(String s, int x) {
return substring(s, x, strL(s));
}
static public String substring(String s, int x, int y) {
if (s == null)
return null;
if (x < 0)
x = 0;
if (x >= s.length())
return "";
if (y < x)
y = x;
if (y > s.length())
y = s.length();
return s.substring(x, y);
}
static public long parseLong(String s) {
if (empty(s))
return 0;
return Long.parseLong(dropSuffix("L", s));
}
static public long parseLong(Object s) {
return Long.parseLong((String) s);
}
static public String jextract(String pat, String s) {
return jextract(pat, javaTok(s));
}
static public String jextract(String pat, List tok) {
List tokpat = javaTok(pat);
jfind_preprocess(tokpat);
int i = jfind(tok, tokpat);
if (i < 0)
return null;
int j = i + l(tokpat) - 2;
return joinSubList(tok, i, j);
}
static public String formatWithThousands(long l) {
return formatWithThousandsSeparator(l);
}
static public double fraction(double d) {
return d % 1;
}
static public String n_fancy2(long l, String singular, String plural) {
return formatWithThousandsSeparator(l) + " " + trim(l == 1 ? singular : plural);
}
static public String n_fancy2(Collection l, String singular, String plural) {
return n_fancy2(l(l), singular, plural);
}
static public String n_fancy2(Map m, String singular, String plural) {
return n_fancy2(l(m), singular, plural);
}
static public String n_fancy2(Object[] a, String singular, String plural) {
return n_fancy2(l(a), singular, plural);
}
static public int iteratorCount_int_close(Iterator i) {
try {
int n = 0;
if (i != null)
while (i.hasNext()) {
i.next();
++n;
}
if (i instanceof AutoCloseable)
((AutoCloseable) i).close();
return n;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String asString(Object o) {
return o == null ? null : o.toString();
}
public static String join(String glue, Iterable strings) {
if (strings == null)
return "";
if (strings instanceof Collection) {
if (((Collection) strings).size() == 1)
return str(first(((Collection) strings)));
}
StringBuilder buf = new StringBuilder();
Iterator i = strings.iterator();
if (i.hasNext()) {
buf.append(i.next());
while (i.hasNext()) buf.append(glue).append(i.next());
}
return buf.toString();
}
public static String join(String glue, String... strings) {
return join(glue, Arrays.asList(strings));
}
static public String join(Iterable strings) {
return join("", strings);
}
static public String join(Iterable strings, String glue) {
return join(glue, strings);
}
public static String join(String[] strings) {
return join("", strings);
}
static public String join(String glue, Pair p) {
return p == null ? "" : str(p.a) + glue + str(p.b);
}
static public ArrayList emptyList() {
return new ArrayList();
}
static public ArrayList emptyList(int capacity) {
return new ArrayList(max(0, capacity));
}
static public ArrayList emptyList(Iterable l) {
return l instanceof Collection ? emptyList(((Collection) l).size()) : emptyList();
}
static public ArrayList emptyList(Object[] l) {
return emptyList(l(l));
}
static public ArrayList emptyList(Class c) {
return new ArrayList();
}
static public String fromLines(Iterable lines) {
StringBuilder buf = new StringBuilder();
if (lines != null)
for (Object line : lines) buf.append(str(line)).append('\n');
return buf.toString();
}
static public String fromLines(String... lines) {
return fromLines(asList(lines));
}
static public IterableIterator toLines(File f) {
return linesFromFile(f);
}
static public List toLines(String s) {
List lines = new ArrayList();
if (s == null)
return lines;
int start = 0;
while (true) {
int i = toLines_nextLineBreak(s, start);
if (i < 0) {
if (s.length() > start)
lines.add(s.substring(start));
break;
}
lines.add(s.substring(start, i));
if (s.charAt(i) == '\r' && i + 1 < s.length() && s.charAt(i + 1) == '\n')
i += 2;
else
++i;
start = i;
}
return lines;
}
static public int toLines_nextLineBreak(String s, int start) {
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '\r' || c == '\n')
return i;
}
return -1;
}
static public A optParam(ThreadLocal tl, A defaultValue) {
return optPar(tl, defaultValue);
}
static public A optParam(ThreadLocal tl) {
return optPar(tl);
}
static public Object optParam(String name, Map params) {
return mapGet(params, name);
}
static public A optParam(Object[] opt, String name, A defaultValue) {
int n = l(opt);
if (n == 1 && opt[0] instanceof Map) {
Map map = (Map) (opt[0]);
return map.containsKey(name) ? (A) map.get(name) : defaultValue;
}
if (!even(l(opt)))
throw fail("Odd parameter length");
for (int i = 0; i < l(opt); i += 2) if (eq(opt[i], name))
return (A) opt[i + 1];
return defaultValue;
}
static public Object optParam(Object[] opt, String name) {
return optParam(opt, name, null);
}
static public boolean structure_showTiming, structure_checkTokenCount;
static public String structure(Object o) {
return structure(o, new structure_Data());
}
static public String structure(Object o, structure_Data d) {
StringWriter sw = new StringWriter();
d.out = new PrintWriter(sw);
structure_go(o, d);
String s = str(sw);
if (structure_checkTokenCount) {
print("token count=" + d.n);
assertEquals("token count", l(javaTokC(s)), d.n);
}
return s;
}
static public void structure_go(Object o, structure_Data d) {
structure_1(o, d);
while (nempty(d.stack)) popLast(d.stack).run();
}
static public void structureToPrintWriter(Object o, PrintWriter out) {
structure_Data d = new structure_Data();
d.out = out;
structure_go(o, d);
}
static public boolean structure_allowShortening = false;
static public class structure_ClassInfo {
public List fields;
public Method customSerializer;
public boolean special, nullInstances;
}
static public class structure_Data {
public PrintWriter out;
public int stringSizeLimit;
public int shareStringsLongerThan = 20;
public boolean noStringSharing = false;
public IdentityHashMap seen = new IdentityHashMap();
public HashMap strings = new HashMap();
public HashSet concepts = new HashSet();
public HashMap infoByClass = new HashMap();
public HashMap persistenceInfo = new HashMap();
public int n;
public List stack = new ArrayList();
public structure_Data append(String token) {
out.print(token);
++n;
return this;
}
public structure_Data append(int i) {
out.print(i);
++n;
return this;
}
public structure_Data append(String token, int tokCount) {
out.print(token);
n += tokCount;
return this;
}
public structure_Data app(String token) {
out.print(token);
return this;
}
public structure_Data app(int i) {
out.print(i);
return this;
}
}
static public void structure_1(final Object o, final structure_Data d) {
try {
if (o == null) {
d.append("null");
return;
}
Class c = o.getClass();
boolean concept = false;
structure_ClassInfo info = d.infoByClass.get(c);
if (info == null) {
d.infoByClass.put(c, info = new structure_ClassInfo());
if ((info.customSerializer = findMethodNamed(c, "_serialize")) != null)
info.special = true;
}
List lFields = info.fields;
if (lFields == null) {
if (o instanceof Number) {
PrintWriter out = d.out;
if (o instanceof Integer) {
int i = ((Integer) o).intValue();
out.print(i);
d.n += i < 0 ? 2 : 1;
return;
}
if (o instanceof Long) {
long l = ((Long) o).longValue();
out.print(l);
out.print("L");
d.n += l < 0 ? 2 : 1;
return;
}
if (o instanceof Short) {
short s = ((Short) o).shortValue();
d.append("sh ");
out.print(s);
d.n += s < 0 ? 2 : 1;
return;
}
if (o instanceof Float) {
d.append("fl ", 2);
quoteToPrintWriter(str(o), out);
return;
}
if (o instanceof Double) {
d.append("d(", 3);
quoteToPrintWriter(str(o), out);
d.append(")");
return;
}
if (o instanceof BigInteger) {
out.print("bigint(");
out.print(o);
out.print(")");
d.n += ((BigInteger) o).signum() < 0 ? 5 : 4;
return;
}
}
if (o instanceof Boolean) {
d.append(((Boolean) o).booleanValue() ? "t" : "f");
return;
}
if (o instanceof Character) {
d.append(quoteCharacter((Character) o));
return;
}
if (o instanceof File) {
d.append("File ").append(quote(((File) o).getPath()));
return;
}
Integer ref = d.seen.get(o);
if (o instanceof String && ref == null)
ref = d.strings.get((String) o);
if (ref != null) {
d.append("t").app(ref);
return;
}
if (!(o instanceof String))
d.seen.put(o, d.n);
else {
String s = d.stringSizeLimit != 0 ? shorten((String) o, d.stringSizeLimit) : (String) o;
if (!d.noStringSharing) {
if (d.shareStringsLongerThan == Integer.MAX_VALUE)
d.seen.put(o, d.n);
if (l(s) >= d.shareStringsLongerThan)
d.strings.put(s, d.n);
}
quoteToPrintWriter(s, d.out);
d.n++;
return;
}
if (o instanceof Set) {
if (((Set) o) instanceof TreeSet) {
d.append(isCISet_gen(((Set) o)) ? "ciset" : "treeset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
d.append(((Set) o) instanceof LinkedHashSet ? "lhs" : "hashset");
structure_1(new ArrayList(((Set) o)), d);
return;
}
String name = c.getName();
if (o instanceof Collection && !startsWith(name, "main$")) {
if (name.equals("java.util.Collections$SynchronizedList") || name.equals("java.util.Collections$SynchronizedRandomAccessList")) {
d.append("sync ");
{
structure_1(unwrapSynchronizedList(((List) o)), d);
return;
}
} else if (name.equals("java.util.LinkedList"))
d.append("ll");
d.append("[");
final int l = d.n;
final Iterator it = ((Collection) o).iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext())
d.append("]");
else {
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(it.next(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext())\r\n d.append(\"]\");\r\n else {\r\n d.sta...";
}
});
return;
}
if (o instanceof Map && !startsWith(name, "main$")) {
if (o instanceof LinkedHashMap)
d.append("lhm");
else if (o instanceof HashMap)
d.append("hm");
else if (o instanceof TreeMap)
d.append(isCIMap_gen(((TreeMap) o)) ? "cimap" : "tm");
else if (name.equals("java.util.Collections$SynchronizedMap") || name.equals("java.util.Collections$SynchronizedSortedMap") || name.equals("java.util.Collections$SynchronizedNavigableMap")) {
d.append("sync ");
{
structure_1(unwrapSynchronizedMap(((Map) o)), d);
return;
}
}
d.append("{");
final int l = d.n;
final Iterator it = ((Map) o).entrySet().iterator();
d.stack.add(new Runnable() {
public boolean v = false;
public Map.Entry e;
public void run() {
if (v) {
d.append("=");
v = false;
d.stack.add(this);
structure_1(e.getValue(), d);
} else {
if (!it.hasNext())
d.append("}");
else {
e = (Map.Entry) it.next();
v = true;
d.stack.add(this);
if (d.n != l)
d.append(", ");
structure_1(e.getKey(), d);
}
}
}
});
return;
}
if (c.isArray()) {
if (o instanceof byte[]) {
d.append("ba ").append(quote(bytesToHex((byte[]) o)));
return;
}
final int n = Array.getLength(o);
if (o instanceof boolean[]) {
String hex = boolArrayToHex((boolean[]) o);
int i = l(hex);
while (i > 0 && hex.charAt(i - 1) == '0' && hex.charAt(i - 2) == '0') i -= 2;
d.append("boolarray ").append(n).app(" ").append(quote(substring(hex, 0, i)));
return;
}
String atype = "array", sep = ", ";
if (o instanceof int[]) {
atype = "intarray";
sep = " ";
}
d.append(atype).append("{");
d.stack.add(new Runnable() {
public int i;
public void run() {
if (i >= n)
d.append("}");
else {
d.stack.add(this);
if (i > 0)
d.append(", ");
structure_1(Array.get(o, i++), d);
}
}
});
return;
}
if (o instanceof Class) {
d.append("class(", 2).append(quote(((Class) o).getName())).append(")");
return;
}
if (o instanceof Throwable) {
d.append("exception(", 2).append(quote(((Throwable) o).getMessage())).append(")");
return;
}
if (o instanceof BitSet) {
BitSet bs = (BitSet) o;
d.append("bitset{", 2);
int l = d.n;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
if (d.n != l)
d.append(", ");
d.append(i);
}
d.append("}");
return;
}
if (name.startsWith("java.") || name.startsWith("javax.")) {
d.append("j ").append(quote(str(o)));
return;
}
if (info.special) {
if (info.customSerializer != null) {
Object o2 = invokeMethod(info.customSerializer, o);
d.append("cu ");
String shortName = dropPrefix("main$", name);
d.append(shortName);
d.out.append(' ');
structure_1(o2, d);
return;
} else if (info.nullInstances) {
d.append("null");
return;
} else
throw fail("unknown special type");
}
String dynName = shortDynamicClassName(o);
if (concept && !d.concepts.contains(dynName)) {
d.concepts.add(dynName);
d.append("c ");
}
TreeSet fields = new TreeSet(new Comparator() {
public int compare(Field a, Field b) {
return stdcompare(a.getName(), b.getName());
}
});
Class cc = c;
while (cc != Object.class) {
for (Field field : getDeclaredFields_cached(cc)) {
String fieldName = field.getName();
if (fieldName.equals("_persistenceInfo"))
d.persistenceInfo.put(c, field);
if ((field.getModifiers() & (java.lang.reflect.Modifier.STATIC | java.lang.reflect.Modifier.TRANSIENT)) != 0)
continue;
fields.add(field);
}
cc = cc.getSuperclass();
}
lFields = asList(fields);
int n = l(lFields);
for (int i = 0; i < n; i++) {
Field f = lFields.get(i);
if (f.getName().equals("this$1")) {
lFields.remove(i);
lFields.add(0, f);
break;
}
}
info.fields = lFields;
} else {
Integer ref = d.seen.get(o);
if (ref != null) {
d.append("t").app(ref);
return;
}
d.seen.put(o, d.n);
}
Field persistenceInfoField = (Field) (d.persistenceInfo.get(c));
Map persistenceInfo = persistenceInfoField == null ? null : (Map) persistenceInfoField.get(o);
LinkedHashMap fv = new LinkedHashMap();
for (Field f : lFields) {
Object value;
try {
value = f.get(o);
} catch (Exception e) {
value = "?";
}
if (value != null && (persistenceInfo == null || !Boolean.FALSE.equals(persistenceInfo.get(f.getName()))))
fv.put(f.getName(), value);
}
String name = c.getName();
String shortName = dropPrefix("main$", name);
if (startsWithDigit(shortName))
shortName = name;
if (concept && eq(fv.get("className"), shortName))
fv.remove("className");
if (o instanceof DynamicObject) {
putAll(fv, (Map) fv.get("fieldValues"));
fv.remove("fieldValues");
shortName = shortDynamicClassName(o);
fv.remove("className");
}
String singleField = fv.size() == 1 ? first(fv.keySet()) : null;
d.append(shortName);
d.n += countDots(shortName) * 2;
final int l = d.n;
final Iterator it = fv.entrySet().iterator();
d.stack.add(new Runnable() {
public void run() {
try {
if (!it.hasNext()) {
if (d.n != l)
d.append(")");
} else {
Map.Entry e = (Map.Entry) it.next();
d.append(d.n == l ? "(" : ", ");
d.append((String) e.getKey()).append("=");
d.stack.add(this);
structure_1(e.getValue(), d);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (!it.hasNext()) {\r\n if (d.n != l)\r\n d.append(\")\");\r\n } else...";
}
});
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Class> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException e) {
return null;
}
}
static public Class getClass(Object o) {
return o instanceof Class ? (Class) o : o.getClass();
}
static public Class getClass(Object realm, String name) {
try {
try {
return getClass(realm).getClassLoader().loadClass(classNameToVM(name));
} catch (ClassNotFoundException e) {
return null;
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public String classNameToVM(String name) {
return name.replace(".", "$");
}
static public boolean regexpFind(String pat, String s) {
return regexpFinds(pat, s);
}
static public String discordTokenRegexp() {
return "[MN][A-Za-z\\d]{23}\\.[\\w-]{6}\\.[\\w-]{27}";
}
static public SelfUser jda_selfUser(JDA jda) {
return jda.getSelfUser();
}
static public String ymd() {
return ymd(now());
}
static public String ymd(long now) {
return year(now) + formatInt(month(now), 2) + formatInt(dayOfMonth(now), 2);
}
static public String hms() {
return hms(now());
}
static public String hms(long time) {
return new SimpleDateFormat("HHmmss").format(time);
}
static public File prepareProgramFile(String name) {
return mkdirsForFile(getProgramFile(name));
}
static public File prepareProgramFile(String progID, String name) {
return mkdirsForFile(getProgramFile(progID, name));
}
static public ZipOutputStream newZipOutputStream(String path) {
return newZipOutputStream(new File(path));
}
static public ZipOutputStream newZipOutputStream(File zip) {
try {
return new ZipOutputStream(newFileOutputStream(zip));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public void zip_addTextFile(ZipOutputStream outZip, String name, String text) {
try {
if (text == null)
return;
outZip.putNextEntry(new ZipEntry(name));
byte[] utf8 = toUtf8(text);
outZip.write(utf8, 0, l(utf8));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public boolean endsWith(String a, String b) {
return a != null && a.endsWith(b);
}
static public boolean endsWith(String a, char c) {
return nempty(a) && lastChar(a) == c;
}
static public boolean endsWith(String a, String b, Matches m) {
if (!endsWith(a, b))
return false;
m.m = new String[] { dropLast(l(b), a) };
return true;
}
static public Field getOpt_findField(Class> c, String field) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) if (f.getName().equals(field))
return f;
_c = _c.getSuperclass();
} while (_c != null);
return null;
}
static public Field makeAccessible(Field f) {
try {
f.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, f);
}
return f;
}
static public Method makeAccessible(Method m) {
try {
m.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, m);
}
return m;
}
static public Constructor makeAccessible(Constructor c) {
try {
c.setAccessible(true);
} catch (Throwable e) {
vmBus_send("makeAccessible_error", e, c);
}
return c;
}
static public RuntimeException asRuntimeException(Throwable t) {
if (t instanceof Error)
_handleError((Error) t);
return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
}
static public boolean neq(Object a, Object b) {
return !eq(a, b);
}
static public String rtrim_fromLines(Collection lines) {
StringBuilder buf = new StringBuilder();
if (lines != null) {
boolean first = true;
for (Object line : lines) {
if (first)
first = false;
else
buf.append('\n');
buf.append(str(line));
}
}
return buf.toString();
}
static public List filterNempty(Collection c) {
List l = new ArrayList();
for (String x : unnull(c)) if (nempty(x))
l.add(x);
return l;
}
static public int countWhere(Collection c, Object... data) {
int n = 0;
if (c != null)
for (Object x : c) if (checkFields(x, data))
++n;
return n;
}
static public Collection values(Map map) {
return map == null ? emptyList() : map.values();
}
static public A keyForValue(B value, Map map) {
return reverseLookup(value, map);
}
static public A keyForValue(Map map, B value) {
return reverseLookup(map, value);
}
static public List toLinesFullTrim(String s) {
List l = new ArrayList();
for (String line : toLines(s)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public List toLinesFullTrim(File f) {
List l = new ArrayList();
for (String line : linesFromFile(f)) if (nempty(line = trim(line)))
l.add(line);
return l;
}
static public String standard_toString(Object o) {
if (o == null)
return "null";
String name = shortClassName(o);
Set fields = fieldNames(o);
if (empty(fields))
return name;
return name + "(" + joinWithComma(mapNonNulls(fields, field -> {
Object value = get(o, field);
if (value == null)
return null;
return field + "=" + str(value);
})) + ")";
}
static public void internalFrameTitlePopupMenuItem(JInternalFrame f, final String name, final Object action) {
internalFrameTitlePopupMenu(f, new VF1() {
public void get(JPopupMenu menu) {
try {
addMenuItem(menu, name, action);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "addMenuItem(menu, name, action)";
}
});
}
static public void minimalFrameSize(Component c, int w, int h) {
Container f = getPIFrame(c);
if (f != null)
setSize(f, max(w, getWidth(f)), max(h, getHeight(f)));
}
static public String defaultThreadName_name;
static public String defaultThreadName() {
if (defaultThreadName_name == null)
defaultThreadName_name = "A thread by " + programID();
return defaultThreadName_name;
}
static public Runnable wrapAsActivity(Object r) {
return toRunnable(r);
}
static public Thread newThread(Object runnable) {
return new Thread(_topLevelErrorHandling(toRunnable(runnable)));
}
static public Thread newThread(Object runnable, String name) {
if (name == null)
name = defaultThreadName();
return new Thread(_topLevelErrorHandling(toRunnable(runnable)), name);
}
static public Thread newThread(String name, Object runnable) {
return newThread(runnable, name);
}
static public Throwable innerException(Throwable e) {
return getInnerException(e);
}
static public Object dm_getModule(Object moduleOrID) {
if (moduleOrID == null || eq(moduleOrID, ""))
return null;
if (isString(moduleOrID) && isIdentifier(((String) moduleOrID)))
return dm_getService(((String) moduleOrID));
if (isStringOrIntOrLong(moduleOrID))
return dm_callOS("getDynModuleByID", str(moduleOrID));
return dm_resolveModule(moduleOrID);
}
static public Object dm_call(Object moduleOrID, String method, Object... args) {
Object mod = dm_getModule(moduleOrID);
if (mod == null)
return null;
AutoCloseable __0 = dm_enter(mod);
try {
return call_withVarargs(mod, method, args);
} finally {
_close(__0);
}
}
static public Object rcall(String method, Object o, Object... args) {
return call_withVarargs(o, method, args);
}
static public List regexpAll(String pattern, String text) {
List matches = new ArrayList();
Matcher matcher = regexp(pattern, text);
while (matcher.find()) matches.add(matcher.group());
return matches;
}
static public Map emptyMap() {
return new HashMap();
}
static public Object vmBus_wrapArgs(Object... args) {
return empty(args) ? null : l(args) == 1 ? args[0] : args;
}
static public Set vm_busListeners_live_cache;
static public Set vm_busListeners_live() {
if (vm_busListeners_live_cache == null)
vm_busListeners_live_cache = vm_busListeners_live_load();
return vm_busListeners_live_cache;
}
static public Set vm_busListeners_live_load() {
return vm_generalIdentityHashSet("busListeners");
}
static public void addIfNotNull(Collection l, A a) {
if (a != null && l != null)
l.add(a);
}
static public Map vm_busListenersByMessage_live_cache;
static public Map vm_busListenersByMessage_live() {
if (vm_busListenersByMessage_live_cache == null)
vm_busListenersByMessage_live_cache = vm_busListenersByMessage_live_load();
return vm_busListenersByMessage_live_cache;
}
static public Map vm_busListenersByMessage_live_load() {
return vm_generalHashMap("busListenersByMessage");
}
static public String dm_makeNewModuleWithParams(String moduleLibID, Object... params) {
return (String) dm_callOS("makeNewModule", moduleLibID, false, "beforeStart", new VF1() {
public void get(Object mod) {
try {
print("Got module: " + dm_mod(mod));
dm_call(mod, "setFields", params);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "print(\"Got module: \" + dm_mod(mod));\r\n dm_call(mod, 'setFields, params);";
}
});
}
static public void dm_showModule(Object module) {
Object stem = dm_getStem(module);
if (stem != null)
dm_callOS("showModule", stem);
}
static public void dm_showModule() {
dm_showModule(dm_current_mandatory_generic());
}
static public String shortClassName(Object o) {
if (o == null)
return null;
Class c = o instanceof Class ? (Class) o : o.getClass();
String name = c.getName();
return shortenClassName(name);
}
static public boolean hasSuperclassShortNamed(Object o, String name) {
Class c = _getClass(o);
while (c != null) if (shortClassNameIs(c, name))
return true;
else
c = c.getSuperclass();
return false;
}
static public void dm_reloadModuleInBackground(Object module) {
dm_callOS("reloadModuleInBackground", dm_getStem(module));
}
static public void dm_reloadModuleInBackground() {
dm_reloadModuleInBackground(dm_current_mandatory_generic());
}
static public double toMinutes(long ms) {
return ms / 60000.0;
}
static public Object swing(Object f) {
return swingAndWait(f);
}
static public A swing(F0 f) {
return (A) swingAndWait(f);
}
static public A swing(IF0 f) {
return (A) swingAndWait(f);
}
static public A revalidate(final A c) {
if (c == null || !c.isShowing())
return c;
{
swing(new Runnable() {
public void run() {
try {
c.revalidate();
c.repaint();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "// magic combo to actually relayout and repaint\r\n c.revalidate();\r\n c.r...";
}
});
}
return c;
}
static public void revalidate(JFrame f) {
revalidate((Component) f);
}
static public void revalidate(JInternalFrame f) {
revalidate((Component) f);
}
static public String dropPrefix(String prefix, String s) {
return s == null ? null : s.startsWith(prefix) ? s.substring(l(prefix)) : s;
}
static public ActionListener actionListenerInNewThread(final Object runnable) {
return actionListenerInNewThread(runnable, null);
}
static public ActionListener actionListenerInNewThread(final Object runnable, final Object instanceToHold) {
if (runnable instanceof ActionListener)
return (ActionListener) runnable;
return new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
startThread("Action Listener", new Runnable() {
public void run() {
try {
AutoCloseable __0 = holdInstance(instanceToHold);
try {
callF(runnable);
} finally {
_close(__0);
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "AutoCloseable __0 = holdInstance(instanceToHold); try {\r\n callF(runnable...";
}
});
} catch (Throwable __e) {
messageBox(__e);
}
}
};
}
static public Map humanizeFormLabel_replacements = litmap("id", "ID", "md5", "MD5");
static public String humanizeFormLabel(String s) {
if (containsSpace(s))
return s;
return firstToUpper(joinWithSpace(replaceElementsUsingMap(splitCamelCase(s), humanizeFormLabel_replacements)).replace("I D", "ID"));
}
static public JTextField jtextfield() {
return jTextField();
}
static public JTextField jtextfield(String text) {
return jTextField(text);
}
static public JTextField jtextfield(Object o) {
return jTextField(o);
}
static public int showForm_defaultGap = 4;
static public int showForm_gapBetweenColumns = 10;
static public JPanel showFormTitled(final String title, final Object... _parts) {
JDesktopPane desktop = mainDesktopPane();
if (desktop != null)
return showInternalFrameFormTitled(desktop, title, _parts);
return swing(new F0() {
public JPanel get() {
try {
final Var frame = new Var();
JPanel panel = showForm_makePanel(false, _parts);
frame.set(showForm_makeFrame(title, panel));
return panel;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new Var frame;\r\n JPanel panel = showForm_makePanel(false, _p...";
}
});
}
static public JPanel showForm_makePanel(Boolean internalFrame, Object... _parts) {
List out = showForm_arrange1(showForm_makeComponents(internalFrame, _parts));
return vstackWithSpacing(out, showForm_defaultGap);
}
static public String or2(String a, String b) {
return nempty(a) ? a : b;
}
static public String or2(String a, String b, String c) {
return or2(or2(a, b), c);
}
static public String stringOptPar(Object[] params, String name) {
return (String) optPar(params, name);
}
static public String gtt(JTextComponent c) {
return getTextTrim(c);
}
static public String gtt(JComboBox cb) {
return getTextTrim(cb);
}
static public A toolTip(A c, final Object toolTip) {
return setToolTipText(c, toolTip);
}
static public A toolTip(Object toolTip, A c) {
return setToolTipText(toolTip, c);
}
static public JButton jPopDownButton(String text, final Object... menuParams) {
return jbutton((empty(text) ? "" : text + " ") + unicode_downPointingTriangle(), new Runnable() {
public void run() {
try {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
String position = (String) (optPar(menuParams, "position"));
fillJPopupMenu(menu, paramsWithout(menuParams, "position"));
if (menu.getComponentCount() != emptyCount) {
JButton btn = heldInstance(JButton.class);
int x = 0;
if (eq(position, "center"))
x = (btn.getWidth() - getPreferredWidth(menu)) / 2;
else if (eq(position, "right"))
x = btn.getWidth() - getPreferredWidth(menu);
menu.show(btn, x, btn.getHeight());
}
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "new JPopupMenu menu;\r\n int emptyCount = menu.getComponentCount();\r\n Str...";
}
});
}
static public File javaxBackupDir_dir;
static public File javaxBackupDir() {
return javaxBackupDir_dir != null ? javaxBackupDir_dir : new File(userHome(), "JavaX-Backup");
}
static public File javaxBackupDir(String sub) {
return newFile(javaxBackupDir(), sub);
}
static public String ymdMinusHms() {
return ymd_minus_hms();
}
static public void inputText(final String msg, final Object action) {
inputText(msg, "", action);
}
static public void inputText(final String msg, final String defaultText, final Object action) {
final Object threadInfo = _threadInfo();
swingLater(new Runnable() {
public void run() {
try {
final JTextField tf = jtextfield(defaultText);
String title = joinStrings(" | ", msg, programName());
JComponent form = showFormTitled(title, unnull(msg), tf, new Runnable() {
public void run() {
try {
vmBus_send("inputtingText_OK", threadInfo, msg, tf);
callF_thread(action, getTextTrim(tf));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "vmBus_send(\"inputtingText_OK\", threadInfo, msg, tf);\r\n callF_thread(ac...";
}
});
renameSubmitButton(form, "OK");
vmBus_send("inputtingText", threadInfo, msg, tf);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final JTextField tf = jtextfield(defaultText);\r\n String title = joinString...";
}
});
}
static public String dm_moduleName() {
return dm_moduleName(assertNotNull(dm_current()));
}
static public String dm_moduleName(Object module) {
return (String) callOpt(dm_getStem(module), "moduleName");
}
static public String f2s(File f) {
return f == null ? null : f.getAbsolutePath();
}
static public String f2s(String s) {
return f2s(newFile(s));
}
static public String f2s(java.nio.file.Path p) {
return p == null ? null : f2s(p.toFile());
}
static public void saveTextFileWithInfoBox(File f, String text) {
saveTextFile(f, text);
fileSavedInfoBox(f);
}
static public File newFile(File base, String... names) {
for (String name : names) base = new File(base, name);
return base;
}
static public File newFile(String name) {
return name == null ? null : new File(name);
}
static public File newFile(String base, String... names) {
return newFile(newFile(base), names);
}
static public String javaTokWordWrap(String s) {
return javaTokWordWrap(120, s);
}
static public String javaTokWordWrap(int cols, String s) {
int col = 0;
List tok = javaTok(s);
for (int i = 0; i < l(tok); i++) {
String t = tok.get(i);
if (odd(i) && col >= cols && !containsNewLine(t))
tok.set(i, t = rtrimSpaces(t) + "\n");
int idx = t.lastIndexOf('\n');
if (idx >= 0)
col = l(t) - (idx + 1);
else
col += l(t);
}
return join(tok);
}
static public String dm_freshModuleStructureWithoutError(Object module) {
dm_clearError(module);
return dm_freshModuleStructure(module);
}
static public File showFileChooserWithDefaultDir(String title, File defaultDir) {
JFileChooser fc = new JFileChooser();
fc.setDialogTitle(title);
fc.setCurrentDirectory(defaultDir);
return execFileChooser(fc);
}
static public boolean fileExists(String path) {
return path != null && new File(path).exists();
}
static public boolean fileExists(File f) {
return f != null && f.exists();
}
static public JWindow infoBox(String text) {
return infoMessage(text);
}
static public JWindow infoBox(String text, double seconds) {
return infoMessage(text, seconds);
}
static public JWindow infoBox(Throwable e) {
return infoMessage(e);
}
static public void dm_replaceModuleWithStructure(Object mod, String struct) {
setAll(dm_getStem(mod), "contentsDirty", false, "oStruct", struct);
dm_reloadModule(mod);
}
static public String loadTextFile(String fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(File f, String defaultContents) {
try {
checkFileNotTooBigToRead(f);
if (f == null || !f.exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public static String loadTextFile(File fileName) {
return loadTextFile(fileName, null);
}
static public String loadTextFile(String fileName, String defaultContents) {
return fileName == null ? defaultContents : loadTextFile(newFile(fileName), defaultContents);
}
static public String loadTextFile(Reader reader) throws IOException {
StringBuilder builder = new StringBuilder();
try {
char[] buffer = new char[1024];
int n;
while (-1 != (n = reader.read(buffer))) builder.append(buffer, 0, n);
} finally {
reader.close();
}
return str(builder);
}
static public void assertTrue(Object o) {
if (!(eq(o, true)))
throw fail(str(o));
}
static public boolean assertTrue(String msg, boolean b) {
if (!b)
throw fail(msg);
return b;
}
static public boolean assertTrue(boolean b) {
if (!b)
throw fail("oops");
return b;
}
static public void dm_reloadMe() {
dm_reloadModule(dm_currentModule());
}
static public JPanel jpanel(LayoutManager layout) {
return swingNu(JPanel.class, layout);
}
static public JPanel jpanel() {
return swingNu(JPanel.class);
}
static public JScrollPane setScrollPaneBackground(Color c, JScrollPane sp) {
if (sp != null && c != null) {
swing(new Runnable() {
public void run() {
try {
sp.getViewport().setBackground(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "sp.getViewport().setBackground(c);";
}
});
}
return sp;
}
static public JScrollPane jscroll(final Component c) {
return swing(new F0() {
public JScrollPane get() {
try {
return new JScrollPane(c);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret new JScrollPane(c);";
}
});
}
static public A withTypeWriterFont(A c) {
return setFont(c, typeWriterFont());
}
static public A swingNu(final Class c, final Object... args) {
return swingConstruct(c, args);
}
static public ThreadLocal componentPopupMenu_mouseEvent;
static public void componentPopupMenu_init() {
{
swing(new Runnable() {
public void run() {
try {
if (componentPopupMenu_mouseEvent == null)
componentPopupMenu_mouseEvent = (ThreadLocal) vm_generalMap_get("mouseEvent");
if (componentPopupMenu_mouseEvent == null)
vm_generalMap_put("componentPopupMenu_mouseEvent", componentPopupMenu_mouseEvent = new ThreadLocal());
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "if (componentPopupMenu_mouseEvent == null)\r\n componentPopupMenu_mouseEve...";
}
});
}
}
static public void componentPopupMenu(final JComponent component, final Object menuMaker) {
if (component == null || menuMaker == null)
return;
{
swing(new Runnable() {
public void run() {
try {
Object adapter = componentPopupMenu_initForComponent(component);
((List) _get(adapter, "maker")).add(menuMaker);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "Object adapter = componentPopupMenu_initForComponent(component);\r\n ((List)...";
}
});
}
}
static public Object componentPopupMenu_initForComponent(final JComponent component) {
return component == null ? null : swing(new F0() {
public Object get() {
try {
componentPopupMenu_init();
Object adapter = findComponentPopupMenuListener_gen(component);
if (adapter == null) {
componentPopupMenu_Adapter a = new componentPopupMenu_Adapter();
component.addMouseListener(a);
adapter = a;
}
return adapter;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "componentPopupMenu_init();\r\n O adapter = findComponentPopupMenuListener_ge...";
}
});
}
static public class componentPopupMenu_Adapter extends MouseAdapter {
public List maker = new ArrayList();
public boolean internalFrameLeftButtonMagic = false;
public Point pressedAt;
public void mousePressed(MouseEvent e) {
displayMenu(e);
pressedAt = internalFrameLeftButtonMagic && e.getClickCount() == 1 && internalFrameActive(e.getComponent()) ? e.getLocationOnScreen() : null;
}
public void mouseReleased(MouseEvent e) {
if (internalFrameLeftButtonMagic && eq(pressedAt, e.getLocationOnScreen()))
displayMenu2(e);
else
displayMenu(e);
}
public void displayMenu(MouseEvent e) {
if (e.getSource() instanceof JInternalFrame)
return;
if (e.isPopupTrigger())
displayMenu2(e);
}
public void displayMenu2(MouseEvent e) {
JPopupMenu menu = new JPopupMenu();
int emptyCount = menu.getComponentCount();
AutoCloseable __0 = tempSetTL(componentPopupMenu_mouseEvent, e);
try {
for (Object menuMaker : maker) pcallF(menuMaker, menu);
vmBus_send("showingPopupMenu", e.getComponent(), menu);
if (menu.getComponentCount() != emptyCount)
menu.show(e.getComponent(), e.getX(), e.getY());
} finally {
_close(__0);
}
}
}
static public void addMenuItem(JPopupMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(JPopupMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public void addMenuItem(JMenu menu, String text, Object action) {
menu.add(jmenuItem(text, action));
}
static public void addMenuItem(Menu menu, String text, Object action) {
menu.add(menuItem(text, action));
}
static public void addMenuItem(JMenu menu, JMenuItem menuItem) {
menu.add(menuItem);
}
static public void clearStringBuffer_gen(Object buf) {
if (buf != null) {
call(buf, "setLength", 0);
call(buf, "trimToSize");
}
}
static public void swingEvery(JComponent component, long delay, Object r) {
installTimer(component, delay, r);
}
static public void swingEvery(JComponent component, long delay, long firstDelay, Object r) {
installTimer(component, r, delay, firstDelay);
}
static public void swingEvery(RootPaneContainer frame, long delay, Object r) {
installTimer(frame, delay, r);
}
static public void swingEvery(RootPaneContainer frame, long delay, long firstDelay, Object r) {
installTimer(frame, delay, firstDelay, r);
}
static public long toMS(double seconds) {
return (long) (seconds * 1000);
}
static public void swingLater(long delay, final Object r) {
javax.swing.Timer timer = new javax.swing.Timer(toInt(delay), actionListener(wrapAsActivity(r)));
timer.setRepeats(false);
timer.start();
}
static public void swingLater(Object r) {
SwingUtilities.invokeLater(toRunnable(r));
}
static public Timer installTimer(JComponent component, Object r, long delay) {
return installTimer(component, r, delay, delay);
}
static public Timer installTimer(RootPaneContainer frame, long delay, Object r) {
return installTimer(frame.getRootPane(), r, delay, delay);
}
static public Timer installTimer(JComponent component, long delay, Object r) {
return installTimer(component, r, delay, delay);
}
static public Timer installTimer(JComponent component, long delay, long firstDelay, Object r) {
return installTimer(component, r, delay, firstDelay);
}
static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay) {
return installTimer(component, r, delay, firstDelay, true);
}
static public Timer installTimer(final JComponent component, final Object r, final long delay, final long firstDelay, final boolean repeats) {
if (component == null)
return null;
return (Timer) swingAndWait(new F0() {
public Object get() {
try {
final Var timer = new Var();
timer.set(new Timer(toInt(delay), new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent _evt) {
try {
AutoCloseable __0 = tempActivity(r);
try {
try {
if (!allPaused())
if (isFalse(callF(r)))
cancelTimer(timer.get());
} catch (Throwable __e) {
_handleException(__e);
}
} finally {
_close(__0);
}
} catch (Throwable __e) {
messageBox(__e);
}
}
}));
timer.get().setInitialDelay(toInt(firstDelay));
timer.get().setRepeats(repeats);
bindTimerToComponent(timer.get(), component);
return timer.get();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "final new Var timer;\r\n timer.set(new Timer(toInt(delay), actionList...";
}
});
}
static public Timer installTimer(RootPaneContainer frame, long delay, long firstDelay, Object r) {
return installTimer(frame.getRootPane(), delay, firstDelay, r);
}
static public StringBuffer liveLocalPrintLog() {
return local_log;
}
static public Object swingCall(final Object o, final String method, final Object... args) {
return swing(new F0() {
public Object get() {
try {
return call(o, method, args);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret call(o, method, args);";
}
});
}
static public Font getFont(JComponent c) {
return c == null ? null : swing(new F0() {
public Font get() {
try {
return c.getFont();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret c.getFont();";
}
});
}
static public int toInt_checked(long l) {
if (l != (int) l)
throw fail("Too large for int: " + l);
return (int) l;
}
static public String strUnnull(Object o) {
return o == null ? "" : str(o);
}
static public String jlabel_textAsHTML_center_ifNeeded(String text) {
if (swic(text, "") && ewic(text, ""))
return text;
if (!containsNewLines(text))
return text;
return jlabel_textAsHTML_center(text);
}
static public List asSynchroList(Iterable l) {
return syncList(cloneList(l));
}
static public void swingAndWait(Runnable r) {
try {
if (isAWTThread())
r.run();
else
EventQueue.invokeAndWait(addThreadInfoToRunnable(r));
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public Object swingAndWait(final Object f) {
if (isAWTThread())
return callF(f);
else {
final Var result = new Var();
swingAndWait(new Runnable() {
public void run() {
try {
result.set(callF(f));
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "result.set(callF(f));";
}
});
return result.get();
}
}
static public boolean isEditableComboBox(final JComboBox cb) {
return cb != null && swing(new F0() {
public Boolean get() {
try {
return cb.isEditable();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret cb.isEditable();";
}
});
}
static public Object collectionMutex(List l) {
return l;
}
static public Object collectionMutex(Object o) {
if (o instanceof List)
return o;
String c = className(o);
if (eq(c, "java.util.TreeMap$KeySet"))
c = className(o = getOpt(o, "m"));
else if (eq(c, "java.util.HashMap$KeySet"))
c = className(o = get_raw(o, "this$0"));
if (eqOneOf(c, "java.util.TreeMap$AscendingSubMap", "java.util.TreeMap$DescendingSubMap"))
c = className(o = get_raw(o, "m"));
return o;
}
static public List _registerWeakMap_preList;
static public A _registerWeakMap(A map) {
if (javax() == null) {
if (_registerWeakMap_preList == null)
_registerWeakMap_preList = synchroList();
_registerWeakMap_preList.add(map);
return map;
}
try {
call(javax(), "_registerWeakMap", map);
} catch (Throwable e) {
printException(e);
print("Upgrade JavaX!!");
}
return map;
}
static public void _onLoad_registerWeakMap() {
assertNotNull(javax());
if (_registerWeakMap_preList == null)
return;
for (Object o : _registerWeakMap_preList) _registerWeakMap(o);
_registerWeakMap_preList = null;
}
static public void raiseFlagAndDo(Flag flag, Runnable r) {
if (flag.raise())
callF(r);
}
static public void _handleException_addHandler(Object handler) {
addIfNotThere(_handleException_onException, handler);
}
static public A assertNull(A a) {
assertTrue(a == null);
return a;
}
static public A assertNull(String msg, A a) {
assertTrue(msg, a == null);
return a;
}
static public class getOpt_Map extends WeakHashMap {
public getOpt_Map() {
if (getOpt_special == null)
getOpt_special = new HashMap();
clear();
}
public void clear() {
super.clear();
put(Class.class, getOpt_special);
put(String.class, getOpt_special);
}
}
static final public Map> getOpt_cache = _registerDangerousWeakMap(synchroMap(new getOpt_Map()));
static public HashMap getOpt_special;
static public Object getOpt_cached(Object o, String field) {
try {
if (o == null)
return null;
Class c = o.getClass();
HashMap map;
synchronized (getOpt_cache) {
map = getOpt_cache.get(c);
if (map == null)
map = getOpt_makeCache(c);
}
if (map == getOpt_special) {
if (o instanceof Class)
return getOpt((Class) o, field);
if (o instanceof Map)
return ((Map) o).get(field);
}
Field f = map.get(field);
if (f != null)
return f.get(o);
if (o instanceof DynamicObject)
return mapGet2(((DynamicObject) o).fieldValues, field);
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
static public HashMap getOpt_makeCache(Class c) {
HashMap map;
if (isSubtypeOf(c, Map.class))
map = getOpt_special;
else {
map = new HashMap();
if (!reflection_classesNotToScan().contains(c.getName())) {
Class _c = c;
do {
for (Field f : _c.getDeclaredFields()) {
makeAccessible(f);
String name = f.getName();
if (!map.containsKey(name))
map.put(name, f);
}
_c = _c.getSuperclass();
} while (_c != null);
}
}
if (getOpt_cache != null)
getOpt_cache.put(c, map);
return map;
}
static public JInternalFrame getInternalFrame(final Object _o) {
return _o == null ? null : swing(new F0() {
public JInternalFrame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JInternalFrame)
return (JInternalFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
}
});
}
static public A internalFrameTitle(A c, final String title) {
final JInternalFrame f = getInternalFrame(c);
if (f != null) {
swing(new Runnable() {
public void run() {
try {
f.setTitle(unnull(title));
toolTip(getInternalFrameTitlePaneComponent(f), title);
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "f.setTitle(unnull(title));\r\n toolTip(getInternalFrameTitlePaneComponent(f)...";
}
});
}
return c;
}
static public A internalFrameTitle(String title, A c) {
return internalFrameTitle(c, title);
}
static public String internalFrameTitle(Component c) {
final JInternalFrame f = getInternalFrame(c);
return f == null ? null : swing(new F0() {
public String get() {
try {
return f.getTitle();
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "ret f.getTitle();";
}
});
}
static public A frameTitle(A c, String title) {
return setFrameTitle(c, title);
}
static public A frameTitle(String title, A c) {
return setFrameTitle(c, title);
}
static public String frameTitle(Component c) {
return getFrameTitle(c);
}
static public JFrame getFrame(final Object _o) {
return swing(new F0() {
public JFrame get() {
try {
Object o = _o;
if (o instanceof ButtonGroup)
o = first(buttonsInGroup((ButtonGroup) o));
if (!(o instanceof Component))
return null;
Component c = (Component) o;
while (c != null) {
if (c instanceof JFrame)
return (JFrame) c;
c = c.getParent();
}
return null;
} catch (Exception __e) {
throw rethrow(__e);
}
}
public String toString() {
return "O o = _o;\r\n if (o instanceof ButtonGroup) o = first(buttonsInGroup((Button...";
}
});
}
static public Set _registerAutoCloseable_set = synchroHashSet();
static public void _registerAutoCloseable(AutoCloseable c) {
addIfNotNull(_registerAutoCloseable_set, c);
}
static public void cleanMeUp__registerAutoCloseable() {
closeAutoCloseables(getAndClearList(_registerAutoCloseable_set));
}
static public Map cloneMap(Map map) {
if (map == null)
return new HashMap();
synchronized (map) {
return map instanceof TreeMap ? new TreeMap((TreeMap) map) : map instanceof LinkedHashMap ? new LinkedHashMap(map) : new HashMap(map);
}
}
static public A callFInRealOrMyMC(Object realm, F0 f) {
return f == null ? null : f.get();
}
static public B callFInRealOrMyMC(Object realm, F1 f, A a) {
return f == null ? null : f.get(a);
}
static public C callFInRealOrMyMC(Object realm, F2 f, A a, B b) {
return f == null ? null : f.get(a, b);
}
static public void callFInRealOrMyMC(Object realm, VF1 f, A a) {
if (f != null)
f.get(a);
}
static public Object callFInRealOrMyMC(Object realm, Object f, Object... args) {
if (f instanceof String) {
Class mc = getMainClass(realm);
if (hasMethod(mc, ((String) f), args))
return call(mc, ((String) f), args);
}
return callF(f, args);
}
static public Object callOpt_withVarargs(Object o, String method, Object... args) {
try {
if (o == null)
return null;
if (o instanceof Class) {
Class c = (Class) o;
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me == null) {
return null;
}
if ((me.getModifiers() & Modifier.STATIC) == 0)
return null;
return invokeMethod(me, null, args);
} else {
Class c = o.getClass();
_MethodCache cache = callOpt_getCache(c);
Method me = cache.findMethod(method, args);
if (me != null)
return invokeMethod(me, o, args);
List