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 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.*;
public class main {
static String snippetID = "#636";
static JTextArea textArea;
static JLabel status;
static JButton btnSave;
public static void main(String[] args) throws Exception {
if (args.length != 0) snippetID = args[0];
snippetID = formatSnippetID(snippetID);
JFrame frame = new JFrame(snippetID + " - Edit");
JPanel panel = new JPanel(new BorderLayout());
textArea = newTypeWriterTextArea();
panel.add(BorderLayout.CENTER, new JScrollPane(textArea));
status = new JLabel("Loading...");
btnSave = new JButton("Save " + snippetID);
btnSave.setEnabled(false);
textArea.setEditable(false); // still loading
btnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent _evt) {
saveSnippet();
}});
JPanel bottom = new JPanel(new BorderLayout());
bottom.add(BorderLayout.CENTER, status);
bottom.add(BorderLayout.EAST, btnSave);
panel.add(BorderLayout.SOUTH, bottom);
onUpdate(textArea, new Runnable() { public void run() { try {
btnSave.setEnabled(true);
} catch (Exception __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}});
Thread _t_0 = new Thread() {
public void run() {
try {
final String s = loadSnippet(snippetID);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
status.setText("Loaded " + s.length() + " chars.");
textArea.setText(s);
//textArea.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
textArea.setCaretPosition(0);
btnSave.setEnabled(false);
textArea.setEditable(true);
textArea.requestFocus();
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_0.start();
frame.add(panel);
frame.setBounds(100, 100, 500, 400);
frame.setVisible(true);
exitOnFrameClose(frame);
}
static void saveSnippet() {
final String text = textArea.getText();
btnSave.setEnabled(false);
status.setText("Saving...");
Thread _t_1 = new Thread() {
public void run() {
try {
final String url = "http://tinybrain.de:8080/tb-int/update_snippet_text.php";
String user = loadTextFile(new File(userHome(), ".tinybrain/username").getPath(), null);
String pass = loadTextFile(new File(userHome(), ".tinybrain/userpass").getPath(), null);
String query = "id=" + parseSnippetID(snippetID) + "&text=" + urlencode(text) + "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
final String page = doPost(query, url);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
status.setText("Saved snippet: " + page);
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
});
} catch (Exception _e) {
throw _e instanceof RuntimeException ? (RuntimeException) _e : new RuntimeException(_e); } }
};
_t_1.start();
}
static String _userHome;
static String userHome() {
if (_userHome == null) {
if (isAndroid())
_userHome = "/storage/sdcard0/";
else
_userHome = System.getProperty("user.home");
//System.out.println("userHome: " + _userHome);
}
return _userHome;
}
public static long parseSnippetID(String snippetID) {
long id = Long.parseLong(shortenSnippetID(snippetID));
if (id == 0) fail("0 is not a snippet ID");
return id;
}
public static String loadTextFile(String fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(String fileName, String defaultContents) throws IOException {
if (!new File(fileName).exists())
return defaultContents;
FileInputStream fileInputStream = new FileInputStream(fileName);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
return loadTextFile(inputStreamReader);
}
public static String loadTextFile(File fileName) {
try {
return loadTextFile(fileName, null);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadTextFile(File fileName, String defaultContents) throws IOException {
try {
return loadTextFile(fileName.getPath(), defaultContents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static 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 builder.toString();
}
static String urlencode(String x) {
try {
return URLEncoder.encode(unnull(x), "UTF-8");
} catch (UnsupportedEncodingException e) { throw new RuntimeException(e); }
}
static boolean preferCached = false;
public static String loadSnippet(String snippetID) {
try {
return loadSnippet(parseSnippetID(snippetID), preferCached);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String loadSnippet(String snippetID, boolean preferCached) throws IOException {
return loadSnippet(parseSnippetID(snippetID), preferCached);
}
public static String loadSnippet(long snippetID, boolean preferCached) throws IOException {
String text;
// boss bot disabled for now for shorter transpilations
/*text = getSnippetFromBossBot(snippetID);
if (text != null) return text;*/
initSnippetCache();
text = DiskSnippetCache_get(snippetID);
if (preferCached && text != null)
return text;
try {
if (text != null) System.err.println("md5: " + md5(text));
URL url = new URL("http://tinybrain.de:8080/getraw.php?id=" + snippetID + "&utf8=1");
text = loadPage(url);
} catch (RuntimeException e) {
e.printStackTrace();
throw new IOException("Snippet #" + snippetID + " not found or not public");
}
try {
initSnippetCache();
DiskSnippetCache_put(snippetID, text);
} catch (IOException e) {
System.err.println("Minor warning: Couldn't save snippet to cache (" + DiskSnippetCache_getDir() + ")");
}
return text;
}
static File DiskSnippetCache_dir;
public static void initDiskSnippetCache(File dir) {
DiskSnippetCache_dir = dir;
dir.mkdirs();
}
public static synchronized String DiskSnippetCache_get(long snippetID) throws IOException {
return loadTextFile(DiskSnippetCache_getFile(snippetID).getPath(), null);
}
private static File DiskSnippetCache_getFile(long snippetID) {
return new File(DiskSnippetCache_dir, "" + snippetID);
}
public static synchronized void DiskSnippetCache_put(long snippetID, String snippet) throws IOException {
saveTextFile(DiskSnippetCache_getFile(snippetID).getPath(), snippet);
}
public static File DiskSnippetCache_getDir() {
return DiskSnippetCache_dir;
}
public static void initSnippetCache() {
if (DiskSnippetCache_dir == null)
initDiskSnippetCache(new File(System.getProperty("user.home"), ".tinybrain/snippet-cache"));
}
static String formatSnippetID(String id) {
return "#" + parseSnippetID(id);
}
static String formatSnippetID(long id) {
return "#" + id;
}
// action = runnable or method name
static void onUpdate(JTextComponent c, final Object r) {
c.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
callFunction(r);
}
public void removeUpdate(DocumentEvent e) {
callFunction(r);
}
public void changedUpdate(DocumentEvent e) {
callFunction(r);
}
});
}
static String doPost(Map urlParameters, String url) {
return doPost(makePostData(urlParameters), url);
}
static String doPost(String urlParameters, String url) { try {
URL _url = new URL(url);
return doPost(urlParameters, _url.openConnection(), _url);
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static String doPost(String urlParameters, URLConnection conn, URL url) { try {
String computerID = getComputerID();
if (computerID != null)
conn.setRequestProperty("X-ComputerID", computerID);
// connect and do POST
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
String contents = loadPage(conn, url);
writer.close();
return contents;
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static JTextArea newTypeWriterTextArea() {
JTextArea textArea = new JTextArea();
textArea.setFont(new Font("Courier", Font.PLAIN, 14));
return textArea;
}
static JTextArea newTypeWriterTextArea(String text) {
JTextArea textArea = newTypeWriterTextArea();
textArea.setText(text);
return textArea;
}
static void exitOnFrameClose(JFrame frame) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
static String unnull(String s) {
return s == null ? "" : s;
}
static List unnull(List l) {
return l == null ? emptyList() : l;
}
static Object callFunction(Object f, Object... args) {
if (f == null) return null;
if (f instanceof Runnable) {
((Runnable) f).run();
return null;
} else if (f instanceof String)
return call(mc(), (String) f, args);
else
return call(f, "get", args);
//else throw fail("Can't call a " + getClassName(f));
}
static ThreadLocal loadPage_charset = new ThreadLocal();
static boolean loadPage_allowGzip = true, loadPage_debug;
public static String loadPageSilently(String url) {
try {
return loadPageSilently(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPageSilently(URL url) {
try {
IOException e = null;
for (int tries = 0; tries < 60; tries++)
try {
URLConnection con = url.openConnection();
return loadPage(con, url);
} catch (IOException _e) {
e = _e;
print("Retrying because of: " + e);
sleepSeconds(1);
}
throw e;
} catch (IOException e) { throw new RuntimeException(e); }
}
static String loadPage_preprocess(String url) {
if (url.startsWith("tb/"))
url = "tinybrain.de:8080/" + url;
if (url.indexOf("://") < 0)
url = "http://" + url;
return url;
}
public static String loadPage(String url) {
try {
return loadPage(new URL(loadPage_preprocess(url)));
} catch (IOException e) { throw new RuntimeException(e); }
}
public static String loadPage(URL url) {
print("Loading: " + url.toExternalForm());
return loadPageSilently(url);
}
public static String loadPage(URLConnection con, URL url) throws IOException {
String computerID = getComputerID();
try {
if (computerID != null)
con.setRequestProperty("X-ComputerID", computerID);
if (loadPage_allowGzip)
con.setRequestProperty("Accept-Encoding", "gzip");
} catch (Throwable e) {} // fails if within doPost
String contentType = con.getContentType();
if (contentType == null)
throw new IOException("Page could not be read: " + url);
//print("Content-Type: " + contentType);
String charset = loadPage_charset == null ? null : loadPage_charset.get();
if (charset == null) charset = loadPage_guessCharset(contentType);
InputStream in = con.getInputStream();
if ("gzip".equals(con.getContentEncoding())) {
if (loadPage_debug)
print("loadPage: Using gzip.");
in = new GZIPInputStream(in);
}
Reader r = new InputStreamReader(in, charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
//Log.info("Chars read: " + buf.length());
buf.append((char) ch);
}
return buf.toString();
}
static String loadPage_guessCharset(String contentType) {
Pattern p = Pattern.compile("text/[a-z]+;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(contentType);
/* If Content-Type doesn't match this pre-conception, choose default and hope for the best. */
return m.matches() ? m.group(1) : "ISO-8859-1";
}
static String getComputerID() { try {
return computerID();
} catch (Throwable __e) { throw __e instanceof RuntimeException ? (RuntimeException) __e : new RuntimeException(__e); }}
static RuntimeException fail() {
throw new RuntimeException("fail");
}
static RuntimeException fail(Object msg) {
throw new RuntimeException(String.valueOf(msg));
}
static RuntimeException fail(String msg) {
throw new RuntimeException(unnull(msg));
}
static RuntimeException fail(String msg, Object... args) {
throw new RuntimeException(format(msg, args));
}
/** writes safely (to temp file, then rename) */
public static void saveTextFile(String fileName, String contents) throws IOException {
File file = new File(fileName);
File parentFile = file.getParentFile();
if (parentFile != null)
parentFile.mkdirs();
String tempFileName = fileName + "_temp";
if (contents != null) {
FileOutputStream fileOutputStream = new FileOutputStream(tempFileName);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
printWriter.print(contents);
printWriter.close();
}
if (file.exists() && !file.delete())
throw new IOException("Can't delete " + fileName);
if (contents != null)
if (!new File(tempFileName).renameTo(file))
throw new IOException("Can't rename " + tempFileName + " to " + fileName);
}
public static void saveTextFile(File fileName, String contents) {
try {
saveTextFile(fileName.getPath(), contents);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static String makePostData(Map