Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

280
LINES

< > BotCompany Repo | #1001018 // Swing: Snippet editor with predictor (v2, with github support)

JavaX source code [tags: use-pretranspiled] - run with: x30.jar

Libraryless. Click here for Pure Java version (2350L/17K/54K).

!752

static S snippetID;
static int maxTokens = 100;
static S fontID = null/*"#1000993"*/;

static S corpusID = "#1001010";
static S predictorID = "#1001028";
static boolean allTokens = true;

static JTextArea textArea;
static JLabel status;
static JButton btnSave;
static JTextArea advisorTextPane;
static JScrollPane textScroller, advisorScroller;
static volatile Object predictor;
static Font fancyFont;

static class MyLayoutManager implements LayoutManager {
  public void addLayoutComponent(String s, Component c) {}
  public void removeLayoutComponent(Component c) {}
  
  public Dimension preferredLayoutSize(Container c) {
    return minimumLayoutSize(c);
  }
  
  public Dimension minimumLayoutSize(Container c) {
    return new Dimension(500, 400);
  }
  
  public void layoutContainer(Container c) {
    int w = c.getWidth(), h = c.getHeight();
    int split = h*2/3;
    textScroller.setBounds(0, 0, w, split);
    advisorScroller.setBounds(0, split, w, h-split);
  }
}

p {
  if (args.length != 0) snippetID = args[0];
  thread { ask(); }
}

svoid ask() {
  corpusID = slte("Corpus ID or GitHub URL:", corpusID);
  if (corpusID != null && !isSnippetID(corpusID)) {
    Matcher m  = matcher("github.com/([^/]+/[^/]+)", corpusID);
    if (m.find())
      github(m.group(1));
    else {
      m  = matcher("([^/]+/[^/]+)", corpusID);
      if (m.matches())
        github(corpusID);
      else {
        print("Unknown corpus reference: " + corpusID);
        corpusID = null;
      }
    }
  }
  awt { go(); }
}
  
svoid go() {
  //snippetID = formatSnippetID(snippetID);
  JFrame frame = new JFrame("Predictive Editor v2");
  JPanel panel2 = new JPanel(new MyLayoutManager());
  
  advisorTextPane = new JTextArea();
  advisorTextPane.setEditable(false);
  advisorTextPane.setLineWrap(true);
  advisorTextPane.setWrapStyleWord(true);
  
  // Prevents scrolling down?
  DefaultCaret caret = (DefaultCaret) advisorTextPane.getCaret();
  caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
  
  if (fontID != null) try {
    fancyFont = loadFont(fontID, 24);
    advisorTextPane.setFont(fancyFont);
  } catch (Throwable e) { e.printStackTrace(); }
  
  //advisorScroller = new JScrollPane(advisorTextPane);
  advisorScroller = new JScrollPane(makeAnimation());
  advisorScroller.setMinimumSize(new Dimension(100, 300));
  
  textArea = new JTextArea();
  textScroller = new JScrollPane(textArea);
  panel2.add(textScroller);
  panel2.add(advisorScroller);
  
  status = new JLabel(" ");
  btnSave = new JButton("Save " + snippetID);
  btnSave.setEnabled(false);
  
  btnSave.addActionListener(actionListener {
    saveSnippet();
  });
  
  JPanel bottom = new JPanel(new BorderLayout);
  bottom.add(BorderLayout.CENTER, status);
  //bottom.add(BorderLayout.EAST, btnSave);
 
  JPanel panel = new JPanel(new BorderLayout);
  panel.add(BorderLayout.CENTER, panel2);
  panel.add(BorderLayout.SOUTH, bottom);
  
  textArea.getDocument().addDocumentListener(new DocumentListener() {
    public void insertUpdate(DocumentEvent e) {
      btnSave.setEnabled(true);
      predict();
    }
    public void removeUpdate(DocumentEvent e) {
      btnSave.setEnabled(true);
      predict();
    }
    public void changedUpdate(DocumentEvent e) {
      // apparently it doesn't occur
    }
  });
  
  textArea.addCaretListener(new CaretListener() {
    public void caretUpdate(CaretEvent e) {
      predict();
    }
  });
  
  if (snippetID != null) {
    textArea.setEditable(false); // still loading
    status.setText("Loading...");
    thread {
      final S s = loadSnippet(snippetID);
      awt {
        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();
      }
    }
  }
  
  frame.addWindowListener(new WindowAdapter() {
    public void windowOpened(WindowEvent e) {
      textArea.requestFocus();
    }
  });
  
  frame.add(panel);
  frame.setBounds(200, 150, 500, 420);
  frame.setVisible(true);
  exitOnFrameClose(frame);
  
  thread {
    loadPredictor();
  }
}

svoid saveSnippet() {
  final S text = textArea.getText();
  btnSave.setEnabled(false);
  status.setText("Saving...");
  thread {
    final S url = "http://tinybrain.de:8080/tb-int/update_snippet_text.php";
    S user = loadTextFile(new File(userHome(), ".tinybrain/username").getPath(), null);
    S pass = loadTextFile(new File(userHome(), ".tinybrain/userpass").getPath(), null);
    S query = "id=" + parseSnippetID(snippetID) + "&text=" + urlencode(text) + "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
    final S page = doPost(query, url);
    
    awt {
      status.setText("Saved snippet: " + page);
    }
  }
}

svoid loadPredictor() ctex {
  // We have the animation instead.
  //advisorShow("Loading predictor...");
  
  Class learner = hotwire(predictorID);
  set(learner, "showGUI", false);
  if (corpusID != null)
    set(learner, "corpusID", corpusID);
  callMain(learner);
  predictor = get(get(learner, "collector"), "winner");
  print("Predictor: " + predictor);
  awt { predict(); }
}

svoid advisorShow(final S text) ctex {
  awt {
    advisorScroller.setViewportView(advisorTextPane);
    advisorTextPane.setText(text);
  }
}

svoid predict() {
  try {
    long startTime = now();
    Object p = predictor;
    if (p == null) return;
    //p = clone(p);
    p = call(p, "derive"); // properly make a local copy
    S text = textArea.getText();
    int idx = textArea.getCaretPosition();
    S previous = safeSubstring(text, 0, idx);
    previous ="\n==\n" + previous; // indicate start of snippet to predictor
    L<S> tok = javaTok(previous);
    if (!allTokens) tok = codeTokensOnly(tok);
    //if (tok.size() != 0) tok.remove(tok.size()-1);
    print(structure(tok));
    S fileName = "#new#";
    
    // make single prediction
    S prediction = cast call(p, "read", fileName, tok);
    new StringBuilder buf;
    
    if (prediction != null) {
      //buf.append(prediction + "\n\n");
      new L<S> multiPrediction;
      S pred = prediction;
      int i = 0;
      while (true) {
        multiPrediction.add(pred);
        if (++i >= maxTokens) break;
        tok.add(pred);
        pred = (String) call(p, "read", fileName, tok);
        if (pred == null) break;
      }
      if (multiPrediction.size() > 1)
        buf.append(join(multiPrediction) + "\n");
    }
    
    advisorShow(buf.toString());
    print((now()-startTime) + " ms");
  } catch (Throwable e) {
    e.printStackTrace();
    // TODO: use "error" font :))))
    advisorShow(e.toString());
  }
}

static L<S> codeTokensOnly(L<S> tok) {
  new L<S> l;
  for (int i = 1; i < tok.size(); i += 2)
    l.add(tok.get(i));
  return l;
}

!include #1001014 // ScalablePane

static JComponent makeAnimation() ctex {
  JLabel label = new JLabel(new ImageIcon(loadLibrary("#1001015").toURI().toURL()));
  label.setText("Loading predictor...");
  label.setVerticalTextPosition(SwingConstants.BOTTOM);
  label.setHorizontalTextPosition(SwingConstants.CENTER);
  /*label.setBackground(Color.white);
  label.setOpaque(true);*/
  return label;
  //return new ScalablePane(ImageIO.read(loadLibrary("#1001013")));
}

svoid github(S githubPath) ctex {
  S url = "https://github.com/" + githubPath + "/archive/master.zip";
  S found = findSnippetNamed("Data: " + url);
  print("Found: " + found);
  if (found != null)
    corpusID = found;
  else {
    S addURL = "http://tinybrain.de:8080/tb-int/add_snippet.php";
    S query = "type=37&high=1&public=1&url=" + urlencode(url);
    corpusID = doPost(query, addURL);
    print(corpusID);
    if (!isSnippetID(corpusID)) {
      print("Github upload failed");
      corpusID = null;
    }
  }
}

Author comment

Began life as a copy of #1001004

download  show line numbers  debug dex  old transpilations   

Travelled to 16 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, onxytkatvevr, pyentgdyhuwx, pzhvpgtvlbxg, teubizvjbppd, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1001018
Snippet name: Swing: Snippet editor with predictor (v2, with github support)
Eternal ID of this version: #1001018/1
Text MD5: dc3261dbf3811e6631d759a6532e99d2
Transpilation MD5: 0f77729a01a703e70582a31d66ff51ee
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-06-15 14:28:30
Source code size: 8127 bytes / 280 lines
Pitched / IR pitched: No / No
Views / Downloads: 698 / 828
Referenced in: [show references]