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

297
LINES

< > BotCompany Repo | #1003873 // Test New #759 (with JavaX Starter)

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

Libraryless. Click here for Pure Java version (5063L/36K/119K).

// The Runner!

!1003872 // neeeeww

static JFrame frame;
static JList list;
static JTextField tfCmd;
static JLabel status;
static JButton btnReload, btnRun, btnClear;
static S submittedInput;
//static JCheckBox cbAll;
static TrayIcon trayIcon;
static volatile boolean searching;
static long lastSearch; // time of last search

static S menuSnippet = "#1000880";
static S menuScript;

static int searchDelay = 100;
static int maxResults = 100;
static int autoResearchInterval = 30000; // 30 secs
static boolean useFastNohup = true; // use pre-spun VMs if available

static L<S> actionHistory = synchroList();

!include #1000839 // PopupMenuHelper

p {
  becomeBotVMIfFirst();
  
  S title = "JavaX Starter"; 
  makeAndroid3(title + ".");
  try {
    frame = new JFrame(title);
  } catch (HeadlessException e) {
    System.out.println("We're headless...");
    return;
  }
  
  setFrameIconLater(frame, "#1003596");
  
  list = new JList();

  new PopupMenuHelper() {
    void fillMenu() {
      try {
        if (menuScript == null)
          menuScript = loadSnippet(menuSnippet);
          
        JMenuItem mi;
        int idx = list.locationToIndex(point);
        final String item = cast list.getModel().getElementAt(idx);
        list.setSelectedIndex(idx);
        
        L<S> tok = javaTok(menuScript);
        for (int i = 1; i+4 < tok.size(); i += 2)
          if (tok.get(i+2).equals("=")) {
            final S snip = unquote(tok.get(i+4));
            S text = unquote(tok.get(i));
            mi = new JMenuItem(text);
            mi.addActionListener(actionListener {
              runCustom(snip, item);
            });
            menu.add(mi);
          }
      } catch (Throwable e) {
        popup(e);
      }
    }
  }.install(list);

  // install double click listener on list    
  list.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent evt) {
      if (evt.getClickCount() == 2) {
        int idx = list.locationToIndex(evt.getPoint());
        final String item = cast list.getModel().getElementAt(idx);
        list.setSelectedIndex(idx);
        runCustom("", item);
      }
    }
  });
  
  // install enter key listener on list
  
  list.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent ke) {
      if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
        run();
      }
    }
  });

  ActionListener go = actionListener {
    tfCmd.selectAll();
    search(true);
  };
 
  btnReload = new JButton(isWindows() ? "Reload" : "\u27F3");
  btnReload.addActionListener(go);

  btnClear = new JButton("X");
  btnClear.setToolTipText("Show latest");
  btnClear.addActionListener(actionListener { tfCmd.setText(""); });

  tfCmd = new JTextField;
  
  /*cbAll = new JCheckBox("Runnables", true);
  cbAll.setToolTipText("Show only runnable programs (not random text snippets)");
  cbAll.addActionListener(go);*/
  
  JPanel controls = new JPanel(new FlowLayout);
  //controls.add(cbAll);
  controls.add(btnReload);
  controls.add(btnClear);

  JPanel north = new JPanel(new BorderLayout);
  north.add(BorderLayout.CENTER, withLabel("Search term:", tfCmd));
  north.add(BorderLayout.EAST, controls);
  
  btnRun = new JButton("Run");
  btnRun.addActionListener(actionListener {
    run();
  });
  
  status = new JLabel(" ");
  JPanel panel = northCenterAndSouth(north, list,
    centerAndEast(status, btnRun));

  tfCmd.addActionListener(go);
  
  frame.addWindowListener(new WindowAdapter() {
    public void windowOpened(WindowEvent e) {
      tfCmd.requestFocus();
    }
    
    public void windowClosing(WindowEvent e) {
      frame.setVisible(false);
    }
    
    public void windowActivated(WindowEvent e) {
      search(false);
    }
  }); 
  
  installTimer(tfCmd, new Runnable() {
    String lastContents;
    boolean autoSearchOn = true;
    
    public void run() {
      String text = getInput();
      if (text.equals(lastContents)) {
        if (now() > lastSearch + autoResearchInterval ||
          (!text.equals(submittedInput) && autoSearchOn && !searching))
          search(false);
      } else
        lastContents = text;
    }
  }, searchDelay);

  frame.add(panel);
  frame.setBounds(100, 100, 500, 400);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  //exitOnFrameClose(frame);
  hideFrameOnMinimize(frame);
  
  trayIcon = installTrayIcon("JavaX!", "#1003596", popupItems());
  
  thread "Updating Menu every 10 minutes" {
    sleepMinutes(10);
    while (licensed()) {
      pcall {
        print("Updating menu.");
        trayIcon.setPopupMenu(makePopupMenu(popupItems()));
      }
      sleepMinutes(10);
    }
  }
  
  hideConsole();
  
  search(false);
}

static O[] popupItems() {
  new L topTenItems;
  pcall {
    L<S> calls = programTopTenWithArgs().getTopTen();
    new Set<S> ids;
    for (S s : calls)
      ids.add(onlyUntilSpace(s));
    Map<S, S> titles = getSnippetTitles(asList(ids));
    
    for (final S call : calls) {
      S id = onlyUntilSpace(call);
      topTenItems.add(menuItem(id + " [" + lookupSnippetID(titles, id) + "]" + (eq(id, call) ? "" : " " + trim(dropPrefix(id, call))),
        r { runCmd(call); }));
    }
  }
    
  ret flattenArray(
    r { bringUpFrame(); }, // on left click
    toObjectArray(topTenItems),
    "***",
    menuItem("Show Runner", r { bringUpFrame(); }),
    menuItem("Show Console", r { showConsole(); }),
    menuItem("Restart Runner", r { restart(); }),
    //menuItem("Hide Console", r { hideConsole(); }),
    menuItem("Exit", r { System.exit(0); }));
}

static S getInput() {
  ret tfCmd.getText().trim();
}

static void search(String cmd, final boolean requestFocus) ctex {
  searching = true;
  try {
    status("Searching " + quote(cmd) + "...");
    if (empty(cmd)) cmd = "_";
    //if (cbAll.isSelected())
      cmd += " type:runnable";
    S page = loadPage("http://tinybrain.de:8080/tb/search.php?q=" + urlencode(cmd) + "&limit=" + maxResults + "&sort=modified");
    Matcher m = Pattern.compile(">(#\\d+)</a> - (.*?)<br>").matcher(page);
    
    final new DefaultListModel model;
    while (m.find()) {
      String title = m.group(2);
      title = join(dropAllTags(htmlcoarsetok(title)));
      model.addElement(htmldecode(m.group(1) + " - " + title));
    }
      
    awt {
      list.setModel(model);
      status("Found " + model.size() + (model.size() == maxResults ? "+" : "") + (true/*cbAll.isSelected()*/ ? " runnable(s)." : " snippet(s)."));
      if (requestFocus)
        tfCmd.requestFocus();
    }
  } finally {
    searching = false;
  }
}

static void status(final S s) {
  awt { status.setText(s); }
}

static void runCmd(final S cmd) {
  print("Running " + cmd);
  S msg = format3("*: Running *", now(), cmd);
  actionHistory.add(msg);
  logQuoted("run.log", msg);
  
  thread { // new thread so we can see progress messages, e.g. for loading the JavaX jar
    if (useFastNohup)
      fastNohupJavax(cmd);
    else
      nohupJavax(cmd);
  }
}

static void runCustom(S worker, S item) {
  if (item == null) ret;
  int i = item.indexOf(' ');
  if (i >= 0) item = item.substring(0, i);
  long id = parseSnippetID(item);
  runCmd(worker + " " + id);
}

static void runWithArguments(S item) {
  // TODO: run a dialog for that
}

static void search(final boolean requestFocus) {
  submittedInput = getInput();
  lastSearch = now();
  final String cmd = submittedInput;
  actionHistory.add(format3("*: Searching *", now(), cmd));
  thread {
    search(cmd, requestFocus);
  }  
}

answer {
  if "very quick java *"
    ret format("ok *", structure(callCalc(veryQuickJava(m.unq(0)))));
}

static void run() {
  S item = cast list.getModel().getElementAt(list.getSelectedIndex());
  runCustom("", item);
}

static void bringUpFrame() {
  makeFrameVisible(frame);
}

Author comment

Began life as a copy of #1000825

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1003873
Snippet name: Test New #759 (with JavaX Starter)
Eternal ID of this version: #1003873/1
Text MD5: 82f43baf6f53c7be32ee9a26e5d083df
Transpilation MD5: f13db804c536b3d74928b2219531a47f
Author: stefan
Category: javax
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2016-07-29 15:31:54
Source code size: 8087 bytes / 297 lines
Pitched / IR pitched: No / No
Views / Downloads: 378 / 416
Referenced in: [show references]