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

426
LINES

< > TinyBrain | #1000825 - JavaX Starter - Runnables search, v3 (CURRENT)

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

Uses 1937K of libraries. Click here for Pure Java version (17915L/136K).

// The Runner!


!7

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

static JTable lastRunTable;
static ReliableSingleThread thread_lastRun;

static S menuSnippet = #1000880;
static S menuScript;
//sS bigIcon = #1101166, smallIcon = #1101181; // the cat
//sS bigIcon = #1101182, smallIcon = #1101184; // cupid/dizzy cat
  // #1101168 // sitting cat
  // #1003596
sS bigIcon = #1101246, smallIcon = #1101184;

static int searchDelay = 100;
static int maxResults = 100;
static int autoResearchInterval = 30000; // 30 secs
static int topTenLookBack = 100; // look at last 100 program runs

static L<S> actionHistory = synchroList();

!include #1001372 // direct nohupJavax

p {
  try {
    new JFrame().dispose();
  } catch {
    System.out.println("We're headless...");
    // TODO: Something useful.
    System.exit(0);
  }

  awtMain();
}

svoid awtMain {
  becomeBotVMIfFirst();
  autoRestart10Mins();
  //mistAqua();
  //magellan();
  //gemini();
  //emeraldDusk();
  //mistSilver();
  //substanceLAF("Raven");
  //substanceLAF("OfficeSilver2007");
  //substanceLAF("OfficeBlue2007");
  //substanceLAF("OfficeBlack2007");
  substanceLAF("Sahara");
  
  print("First-check.");
  first = empty(sendToAll("JavaX Starter.", "activate"));
  print("  ==> " + first);
    
  swing {
    frame = showFrame();
    moveFrameAround(frame);
  }
  
  updateTitle();
  makeAndroid3("JavaX Starter.");
  
  setFrameIconLater(frame, bigIcon); 
  
  // Show the rays
  disposeWindowOnClick(showAnimation("#1003828", 3.5));
  
  swing {
    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+6 < tok.size(); i += 2)
            if (tok.get(i+2).equals("=") && tok.get(i+4).equals("#")) {
              final S snip = unquote(tok.get(i+6));
              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    
    onDoubleClick(list, voidfunc(S item) {
      if (nempty(item))
        runCustom("", item);
    });
    
    // install enter key listener on list
    
    onEnter(list, f runSelected);
  
    final ActionListener go = actionListener {
      tfCmd.selectAll();
      search(true);
    };
   
    btnReload = new JButton(isWindows() ? "Reload" : "\u27F3");
    btnReload.setToolTipText("Search again (if our " + autoResearchInterval/1000 + "s update interval is not enough for you)");
    btnReload.addActionListener(go);
  
    btnClear = new JButton("X");
    btnClear.setToolTipText("Show latest");
    btnClear.addActionListener(actionListener { tfCmd.setText(""); });
  
    tfCmd = new JTextField;
    
    cbPrograms = new JCheckBox("Programs", true);
    cbPrograms.setToolTipText("Show only runnable programs (not random text snippets)");
    cbPrograms.addActionListener(go);
    
    JPanel controls = jflow(btnClear, cbPrograms, btnReload);
  
    JPanel north = centerAndEast(
       withLabel("Search term:", tfCmd),
       controls);
    
    btnRun = jbutton("Run", r { main.runSelected() });
    listDependButton(list, btnRun);
    
    status = new JLabel(" ");
    JPanel searchPanel = 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() {
        updateTitle();
        String text = getInput();
        if (text.equals(lastContents)) {
          if (
            isFocusedWindow(frame) && now() > lastSearch + autoResearchInterval
            
          || (!text.equals(submittedInput) && autoSearchOn && !searching))
            search(false);
        } else
          lastContents = text;
      }
    }, searchDelay);
    
    lastRunTable = sexyTableWithoutDrag();
    onDoubleClickOrEnter(lastRunTable, voidfunc(Int row) {
      Map map = getTableLineAsMap(lastRunTable, row);
      S id = getString(map, "Program ID");
      S args = getString(map, "Arguments");
      runCustom("", id + " " + args);
    });
    
    thread_lastRun = new ReliableSingleThread(r { lastRunTable_update(lastRunTable) });
    thread_lastRun.go();
    
    JTable injectionsTable = jInjectionsTable();
    
    frame.add(jRightTabs("Search", searchPanel, "Last Run Programs", tableWithSearcher(lastRunTable), "Running", injectionsTable));
    frame.setBounds(100, 100, 500, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    hideFrameOnMinimize(frame);
    
    addMenu(frame, "Starter",
      "Show Talk Program [Eleutheria]", r { talkProgram() },
      "Your Computer ID: " + computerID(), r {},
      "Update JavaX", r { nohupJavax(#1001639) },
      "Log in", r { nohupJavax(#1000896) },
      "Exit", r-thread { cleanKill() });
      
    thread { addAISuiteMenu(frame, "AI"); }
    
    if (first)
      trayIcon = installTrayIcon("JavaX!", smallIcon, trayPopupMenuItems());
    
    thread "Updating Menu every 10 minutes" {
      sleepMinutes(10);
      while (licensed()) {
        pcall {
          print("Updating menu.");
          updateMenu();
        }
        sleepMinutes(10);
      }
    }
  
    onUserUtterance(voidfunc(S s) { setTextSelectAll(tfCmd, s); search(false); });
    
    if (myVMPort() == 5000)
      /*if (isStefansPC()) // isMultiCore()
        thread "Warming Up Java" {
          loading "Warming Up Java" { warmUpJavaCompiler(20); }
        }*/
    
    hideConsole();
    
    thread "Start Bots" {
      startInternetTrafficCountBot();
      startVMLister_onChange = r {
        L<startVMLister_Data> hidden = startVMLister_hiddenVMs();
        trayIcon.setToolTip("JavaX: " 
          + n(startVMLister_numVMs(), "VM")
          + (empty(hidden) ? "" : " (" + l(hidden) + " hidden)"));
        updateMenu();
      };
      
      if (startVMLister())
        doEvery(60000, f startVMLister_scan);
        
      startBotHere("Compiler Bot", #1007916);
      
      // TODO: restart these bots if multiple runners are started
      // and exited in unfortunate order
    }
  } // swing
  
  search(false);
}

svoid updateTitle {
  S title = "JavaX Starter v3";
  if (isOfflineMode()) title += " [OFFLINE MODE]";
  setFrameTitle(frame, title);
}

svoid updateMenu {
  updateTitle();
  trayIcon.setPopupMenu(makePopupMenu(dropFirst(trayPopupMenuItems())));
}

static O[] trayPopupMenuItems() {
  new L topTenItems;
  pcall {
    L<S> calls = programTopTenWithArgs(topTenLookBack).getTopTen();
    new HashSet<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 { runProgram(call); }));
    }
  }
  
  //Menu catMenu = new Menu("Cat (Personal Voice Assistant)");
  //catMenu.add(menuItem("Start Listening", f cat_startListening));
  //catMenu.add(menuItem("Stop Listening", f cat_stopListening));
  
  new L hiddenVMItems;
  L<startVMLister_Data> hiddenVMs = startVMLister_hiddenVMs();
  if (nempty(hiddenVMs)) {
    hiddenVMItems.add("***");
    int i = 0;
    for (final startVMLister_Data vm : hiddenVMs) {
      Menu subMenu = new("Hidden VM " + ++i);
      addMenuItem(subMenu, "Kill", r { killVM(vm.port) }); // TODO: use VM ID
      addMenuItem(subMenu, "Restart", r { restartVM(vm.port) });
      addMenuItem(subMenu, "Show Console", r { send(vm.port, "show console") });
      hiddenVMItems.add(subMenu);
    }
  }
    
  ret flattenArray(
    r { bringUpFrame(); }, // on left click
    toObjectArray(topTenItems),
    toObjectArray(hiddenVMItems),
    "***",
    menuItem("Start Listening", f cat_startListening),
    menuItem("Stop Listening", f cat_stopListening),
    menuItem("Show JavaX Starter", f bringUpFrame),
    menuItem("Show Console", f showConsole),
    menuItem("Show All Consoles", f showAllConsoles),
    menuItem("Restart JavaX Starter", f restart),
    menuItem("Show Talk Program [Eleutheria]", f talkProgram),
    //menuItem("Hide Console", f hideConsole),
    isOfflineMode()
      ? menuItem("Switch to online mode", r { goOnlineMode(); updateMenu(); })
      : menuItem("Switch to offline mode", r { goOfflineMode(); updateMenu(); }),
    menuItem("Update JavaX", r { nohupJavax(#1001639) }),
    menuItem("Exit", r { System.exit(0); }));
}

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

static void search(S cmd, final boolean requestFocus) ctex {
  searching = true;
  try {
    status("Searching " + quote(cmd) + "...");
    if (empty(cmd)) cmd = "_";
    if (cbPrograms.isSelected())
      cmd += " type:runnable-desktop";
    fL<Snippet> snippets = tbSearch_url(tb_mainServer() + "/tb/search.php?q=" + urlencode(cmd) + "&limit=" + maxResults + "&sort=modified&quick=1" + standardCredentials());

    final new DefaultListModel model;
    for (Snippet s : snippets)
      model.addElement(fsI(s.id) + " - " + s.title);

    fS _cmd = cmd;

    awt {
      list.setModel(model);
      status("Found " + model.size() + (model.size() == maxResults ? "+" : "") + (cbPrograms.isSelected() ? " runnable(s)." : " snippet(s)."));
      if (requestFocus)
        tfCmd.requestFocus();
      saveTextFile(programFile("search-results.txt"), struct(litmap(date := now(), query := _cmd, results := snippets)));
    }
  } finally {
    searching = false;
  }
}

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

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

static void runHotwired(final S worker, final long id) {
  print("Hotwiring " + worker + " on " + id);
  S msg = format3("*: Hotwiring * on *", now(), worker, id);
  actionHistory.add(msg);
  logQuoted("run.log", msg);
  
  thread {
    _run(worker, new S[] {str(id)}); // TODO: cache code?
  }
}

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);
  print("runCustom: " + id + " [" + worker + "]");
  if (empty(worker))
    runProgram(str(id));
  else
    runHotwired(worker, id);
  minimizeFrame(frame);
}

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)))));
  if "restart" { restart(); ret "OK"; }
  if "activate" { activateFrame(frame); ret "OK"; }
}

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

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

Author comment

Began life as a copy of #1000794

download  show line numbers  debug dex   

Travelled to 111 computer(s): acumhimkfssw, afbdgwpgxusd, afvcxyesxakz, agxbjmyenqqu, ahczwtoujzjf, ajlfxifxfcul, aoiabmzegqzx, aovkdhyilamm, ayfdnjdhpjha, bkpbhqsukdzp, bmzxzaunwzbi, btpsnmddmadp, bvmoasoxxqgd, cbybwowwnfue, cfunsshuasjs, ciwybxsoqrky, cysqohhbtkwd, ddnzoavkxhuk, dhtvkmknsjym, dpnavvvsbarw, dyfxnkwhunql, estmjqchrwzt, etmzoiygucik, fauvpijqivwj, fehiwqupcyrn, fqdbqewsovaa, gwrvuhgaqvyk, hacelcvcghbr, hszllmzzlmie, htvoczylgtdf, icbjsuppbenm, ijsbnqcsyaaf, ilscnaqoeozw, imzmzdywqqli, ishmyahliavo, jdobfzanukfo, jlatgrcjtklg, jmyaexzvplwz, jtubtzbbkimh, kltaiputbqfu, kuyjpjqxmspc, kzsysduheldy, lhdilzshxjzv, liwcxgsjrgqn, lulzaavyztxj, mdelbdmbyvbi, meaugxdlecrj, mjouhigkdmyk, moomcjjtfopu, mqqgnosmbjvj, nbgitpuheiab, ndzpjzzthwet, ngbrtomqtpjn, nnmtytuibrzp, ntqcuorowftz, nysugtttblhj, obpsxxvyfitp, omkuifhlbvuf, omzkqqnokwlv, onfqjnomoxuw, onxytkatvevr, ozfokkltgguo, picgnzycjide, pmilglshkwnf, ppjhyzlbdabe, pwiztjibzslt, qjimsvlqbazf, rcljlypqyydo, rjkjhqualmce, rlljfxnwkesy, rsdhgwlghzqg, rwunbfjijphy, sawdedvomwva, sdspifkayxrz, sftlboijnymy, sgthpswjdnle, svvfvzndtrpq, swnlqaquhrsn, teubizvjbppd, tgvutoijlajd, tntrlsqmulic, tpsnldywmnmr, tvejysmllsmz, uwnvikuolobj, vaduqbtgckcl, vlnhzwvsylal, vmiuuieieuib, vpdwwinrgdga, vqftxbmjmmzu, vzpxdoxhqfnw, weqtezgcwmja, wglhsqxgxbdq, wltunwwkxhxr, wtqryiryparv, wvjjrydmpdin, xbzdlvvdvlsr, xfbsdwenvhih, xhsrmoityime, xidunzvaqbkw, xinetxnxrdbb, xiskaoettebs, xjxehkwqodvf, xlripclqcsxi, xprdwmaupziu, ychswryhhvyu, ydilcnlqtmvn, yktzofexzwjw, yscklbrkmvrk, yugkrbstzyuu, zluxfztcnsid, zsvsackdotgc

No comments. add comment

Snippet ID: #1000825
Snippet name: JavaX Starter - Runnables search, v3 (CURRENT)
Eternal ID of this version: #1000825/80
Text MD5: 1a6504388b43ce8e31d7b77cac740c5d
Transpilation MD5: b9bbf6027200ecc4686efe1e1004b4a4
Author: stefan
Category: javax
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-06-10 21:52:51
Source code size: 12845 bytes / 426 lines
Pitched / IR pitched: No / No
Views / Downloads: 1215 / 71553
Version history: 79 change(s)
Referenced in: [show]