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).

1  
!752
2  
3  
static S snippetID;
4  
static int maxTokens = 100;
5  
static S fontID = null/*"#1000993"*/;
6  
7  
static S corpusID = "#1001010";
8  
static S predictorID = "#1001028";
9  
static boolean allTokens = true;
10  
11  
static JTextArea textArea;
12  
static JLabel status;
13  
static JButton btnSave;
14  
static JTextArea advisorTextPane;
15  
static JScrollPane textScroller, advisorScroller;
16  
static volatile Object predictor;
17  
static Font fancyFont;
18  
19  
static class MyLayoutManager implements LayoutManager {
20  
  public void addLayoutComponent(String s, Component c) {}
21  
  public void removeLayoutComponent(Component c) {}
22  
  
23  
  public Dimension preferredLayoutSize(Container c) {
24  
    return minimumLayoutSize(c);
25  
  }
26  
  
27  
  public Dimension minimumLayoutSize(Container c) {
28  
    return new Dimension(500, 400);
29  
  }
30  
  
31  
  public void layoutContainer(Container c) {
32  
    int w = c.getWidth(), h = c.getHeight();
33  
    int split = h*2/3;
34  
    textScroller.setBounds(0, 0, w, split);
35  
    advisorScroller.setBounds(0, split, w, h-split);
36  
  }
37  
}
38  
39  
p {
40  
  if (args.length != 0) snippetID = args[0];
41  
  thread { ask(); }
42  
}
43  
44  
svoid ask() {
45  
  corpusID = slte("Corpus ID or GitHub URL:", corpusID);
46  
  if (corpusID != null && !isSnippetID(corpusID)) {
47  
    Matcher m  = matcher("github.com/([^/]+/[^/]+)", corpusID);
48  
    if (m.find())
49  
      github(m.group(1));
50  
    else {
51  
      m  = matcher("([^/]+/[^/]+)", corpusID);
52  
      if (m.matches())
53  
        github(corpusID);
54  
      else {
55  
        print("Unknown corpus reference: " + corpusID);
56  
        corpusID = null;
57  
      }
58  
    }
59  
  }
60  
  awt { go(); }
61  
}
62  
  
63  
svoid go() {
64  
  //snippetID = formatSnippetID(snippetID);
65  
  JFrame frame = new JFrame("Predictive Editor v2");
66  
  JPanel panel2 = new JPanel(new MyLayoutManager());
67  
  
68  
  advisorTextPane = new JTextArea();
69  
  advisorTextPane.setEditable(false);
70  
  advisorTextPane.setLineWrap(true);
71  
  advisorTextPane.setWrapStyleWord(true);
72  
  
73  
  // Prevents scrolling down?
74  
  DefaultCaret caret = (DefaultCaret) advisorTextPane.getCaret();
75  
  caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
76  
  
77  
  if (fontID != null) try {
78  
    fancyFont = loadFont(fontID, 24);
79  
    advisorTextPane.setFont(fancyFont);
80  
  } catch (Throwable e) { e.printStackTrace(); }
81  
  
82  
  //advisorScroller = new JScrollPane(advisorTextPane);
83  
  advisorScroller = new JScrollPane(makeAnimation());
84  
  advisorScroller.setMinimumSize(new Dimension(100, 300));
85  
  
86  
  textArea = new JTextArea();
87  
  textScroller = new JScrollPane(textArea);
88  
  panel2.add(textScroller);
89  
  panel2.add(advisorScroller);
90  
  
91  
  status = new JLabel(" ");
92  
  btnSave = new JButton("Save " + snippetID);
93  
  btnSave.setEnabled(false);
94  
  
95  
  btnSave.addActionListener(actionListener {
96  
    saveSnippet();
97  
  });
98  
  
99  
  JPanel bottom = new JPanel(new BorderLayout);
100  
  bottom.add(BorderLayout.CENTER, status);
101  
  //bottom.add(BorderLayout.EAST, btnSave);
102  
 
103  
  JPanel panel = new JPanel(new BorderLayout);
104  
  panel.add(BorderLayout.CENTER, panel2);
105  
  panel.add(BorderLayout.SOUTH, bottom);
106  
  
107  
  textArea.getDocument().addDocumentListener(new DocumentListener() {
108  
    public void insertUpdate(DocumentEvent e) {
109  
      btnSave.setEnabled(true);
110  
      predict();
111  
    }
112  
    public void removeUpdate(DocumentEvent e) {
113  
      btnSave.setEnabled(true);
114  
      predict();
115  
    }
116  
    public void changedUpdate(DocumentEvent e) {
117  
      // apparently it doesn't occur
118  
    }
119  
  });
120  
  
121  
  textArea.addCaretListener(new CaretListener() {
122  
    public void caretUpdate(CaretEvent e) {
123  
      predict();
124  
    }
125  
  });
126  
  
127  
  if (snippetID != null) {
128  
    textArea.setEditable(false); // still loading
129  
    status.setText("Loading...");
130  
    thread {
131  
      final S s = loadSnippet(snippetID);
132  
      awt {
133  
        status.setText("Loaded " + s.length() + " chars.");
134  
        textArea.setText(s);
135  
        //textArea.scrollRectToVisible(new Rectangle(0, 0, 1, 1));
136  
        textArea.setCaretPosition(0);
137  
        btnSave.setEnabled(false);
138  
        textArea.setEditable(true);
139  
        textArea.requestFocus();
140  
      }
141  
    }
142  
  }
143  
  
144  
  frame.addWindowListener(new WindowAdapter() {
145  
    public void windowOpened(WindowEvent e) {
146  
      textArea.requestFocus();
147  
    }
148  
  });
149  
  
150  
  frame.add(panel);
151  
  frame.setBounds(200, 150, 500, 420);
152  
  frame.setVisible(true);
153  
  exitOnFrameClose(frame);
154  
  
155  
  thread {
156  
    loadPredictor();
157  
  }
158  
}
159  
160  
svoid saveSnippet() {
161  
  final S text = textArea.getText();
162  
  btnSave.setEnabled(false);
163  
  status.setText("Saving...");
164  
  thread {
165  
    final S url = "http://tinybrain.de:8080/tb-int/update_snippet_text.php";
166  
    S user = loadTextFile(new File(userHome(), ".tinybrain/username").getPath(), null);
167  
    S pass = loadTextFile(new File(userHome(), ".tinybrain/userpass").getPath(), null);
168  
    S query = "id=" + parseSnippetID(snippetID) + "&text=" + urlencode(text) + "&_user=" + urlencode(user) + "&_pass=" + urlencode(pass);
169  
    final S page = doPost(query, url);
170  
    
171  
    awt {
172  
      status.setText("Saved snippet: " + page);
173  
    }
174  
  }
175  
}
176  
177  
svoid loadPredictor() ctex {
178  
  // We have the animation instead.
179  
  //advisorShow("Loading predictor...");
180  
  
181  
  Class learner = hotwire(predictorID);
182  
  set(learner, "showGUI", false);
183  
  if (corpusID != null)
184  
    set(learner, "corpusID", corpusID);
185  
  callMain(learner);
186  
  predictor = get(get(learner, "collector"), "winner");
187  
  print("Predictor: " + predictor);
188  
  awt { predict(); }
189  
}
190  
191  
svoid advisorShow(final S text) ctex {
192  
  awt {
193  
    advisorScroller.setViewportView(advisorTextPane);
194  
    advisorTextPane.setText(text);
195  
  }
196  
}
197  
198  
svoid predict() {
199  
  try {
200  
    long startTime = now();
201  
    Object p = predictor;
202  
    if (p == null) return;
203  
    //p = clone(p);
204  
    p = call(p, "derive"); // properly make a local copy
205  
    S text = textArea.getText();
206  
    int idx = textArea.getCaretPosition();
207  
    S previous = safeSubstring(text, 0, idx);
208  
    previous ="\n==\n" + previous; // indicate start of snippet to predictor
209  
    L<S> tok = javaTok(previous);
210  
    if (!allTokens) tok = codeTokensOnly(tok);
211  
    //if (tok.size() != 0) tok.remove(tok.size()-1);
212  
    print(structure(tok));
213  
    S fileName = "#new#";
214  
    
215  
    // make single prediction
216  
    S prediction = cast call(p, "read", fileName, tok);
217  
    new StringBuilder buf;
218  
    
219  
    if (prediction != null) {
220  
      //buf.append(prediction + "\n\n");
221  
      new L<S> multiPrediction;
222  
      S pred = prediction;
223  
      int i = 0;
224  
      while (true) {
225  
        multiPrediction.add(pred);
226  
        if (++i >= maxTokens) break;
227  
        tok.add(pred);
228  
        pred = (String) call(p, "read", fileName, tok);
229  
        if (pred == null) break;
230  
      }
231  
      if (multiPrediction.size() > 1)
232  
        buf.append(join(multiPrediction) + "\n");
233  
    }
234  
    
235  
    advisorShow(buf.toString());
236  
    print((now()-startTime) + " ms");
237  
  } catch (Throwable e) {
238  
    e.printStackTrace();
239  
    // TODO: use "error" font :))))
240  
    advisorShow(e.toString());
241  
  }
242  
}
243  
244  
static L<S> codeTokensOnly(L<S> tok) {
245  
  new L<S> l;
246  
  for (int i = 1; i < tok.size(); i += 2)
247  
    l.add(tok.get(i));
248  
  return l;
249  
}
250  
251  
!include #1001014 // ScalablePane
252  
253  
static JComponent makeAnimation() ctex {
254  
  JLabel label = new JLabel(new ImageIcon(loadLibrary("#1001015").toURI().toURL()));
255  
  label.setText("Loading predictor...");
256  
  label.setVerticalTextPosition(SwingConstants.BOTTOM);
257  
  label.setHorizontalTextPosition(SwingConstants.CENTER);
258  
  /*label.setBackground(Color.white);
259  
  label.setOpaque(true);*/
260  
  return label;
261  
  //return new ScalablePane(ImageIO.read(loadLibrary("#1001013")));
262  
}
263  
264  
svoid github(S githubPath) ctex {
265  
  S url = "https://github.com/" + githubPath + "/archive/master.zip";
266  
  S found = findSnippetNamed("Data: " + url);
267  
  print("Found: " + found);
268  
  if (found != null)
269  
    corpusID = found;
270  
  else {
271  
    S addURL = "http://tinybrain.de:8080/tb-int/add_snippet.php";
272  
    S query = "type=37&high=1&public=1&url=" + urlencode(url);
273  
    corpusID = doPost(query, addURL);
274  
    print(corpusID);
275  
    if (!isSnippetID(corpusID)) {
276  
      print("Github upload failed");
277  
      corpusID = null;
278  
    }
279  
  }
280  
}

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: 640 / 750
Referenced in: [show references]