proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/keys/RemoteKeyPanel.java
RemoteKeyPanel
setKeyData
class RemoteKeyPanel extends JPanel { private SessionInfo info; private JTextField txtKeyFile; private JButton btnGenNewKey, btnRefresh, btnAdd, btnRemove, btnEdit; private JTextArea txtPubKey; private Consumer<?> callback1, callback2; private Consumer<String> callback3; private DefaultListModel<String> model; private JList<String> jList; public RemoteKeyPanel(SessionInfo info, Consumer<?> callback1, Consumer<?> callback2, Consumer<String> callback3) { super(new BorderLayout()); this.info = info; this.info = info; this.callback1 = callback1; // this.callback2 = callback2; this.callback2 = callback3; JLabel lblTitle = new JLabel("Public key file:"); txtKeyFile = new SkinnedTextField(20);// new JTextField(20); txtKeyFile.setBorder(null); txtKeyFile.setBackground(App.SKIN.getDefaultBackground()); txtKeyFile.setEditable(false); Box hbox = Box.createHorizontalBox(); hbox.setBorder(new EmptyBorder(10, 10, 10, 10)); hbox.add(lblTitle); hbox.add(Box.createHorizontalStrut(10)); hbox.add(Box.createHorizontalGlue()); hbox.add(txtKeyFile); txtPubKey = new SkinnedTextArea(); txtPubKey.setLineWrap(true); JScrollPane jScrollPane = new SkinnedScrollPane(txtPubKey); btnGenNewKey = new JButton("Generate new key"); btnRefresh = new JButton("Refresh"); btnGenNewKey.addActionListener(e -> { callback1.accept(null); }); btnRefresh.addActionListener(e -> { callback2.accept(null); }); Box hbox1 = Box.createHorizontalBox(); hbox1.add(Box.createHorizontalGlue()); hbox1.add(btnGenNewKey); hbox1.add(Box.createHorizontalStrut(10)); hbox1.add(btnRefresh); hbox1.setBorder(new EmptyBorder(10, 10, 10, 10)); JPanel hostKeyPanel = new JPanel(new BorderLayout()); hostKeyPanel.add(hbox, BorderLayout.NORTH); hostKeyPanel.add(jScrollPane); hostKeyPanel.add(hbox1, BorderLayout.SOUTH); model = new DefaultListModel<>(); jList = new JList<>(model); jList.setBackground(App.SKIN.getTextFieldBackground()); btnAdd = new JButton("Add"); btnEdit = new JButton("Edit"); btnRemove = new JButton("Remove"); btnAdd.addActionListener(e -> { String text = JOptionPane.showInputDialog(null, "New entry"); if (text != null && text.length() > 0) { model.addElement(text); callback3.accept(getAuthorizedKeys()); } }); btnEdit.addActionListener(e -> { int index = jList.getSelectedIndex(); if (index < 0) { JOptionPane.showMessageDialog(null, "No entry is selected"); return; } String str = model.get(index); String text = JOptionPane.showInputDialog(null, "New entry", str); if (text != null && text.length() > 0) { model.set(index, text); callback3.accept(getAuthorizedKeys()); } }); btnRemove.addActionListener(e -> { int index = jList.getSelectedIndex(); if (index < 0) { JOptionPane.showMessageDialog(null, "No entry is selected"); return; } model.remove(index); callback3.accept(getAuthorizedKeys()); }); Box boxBottom = Box.createHorizontalBox(); boxBottom.add(Box.createHorizontalGlue()); boxBottom.add(btnAdd); boxBottom.add(Box.createHorizontalStrut(10)); boxBottom.add(btnEdit); boxBottom.add(Box.createHorizontalStrut(10)); boxBottom.add(btnRemove); boxBottom.setBorder(new EmptyBorder(10, 10, 10, 10)); Box hbox2 = Box.createHorizontalBox(); hbox2.setBorder(new EmptyBorder(10, 10, 10, 10)); hbox2.add(new JLabel("Authorized keys")); hbox2.add(Box.createHorizontalStrut(10)); JPanel authorizedKeysPanel = new JPanel(new BorderLayout()); authorizedKeysPanel.add(hbox2, BorderLayout.NORTH); JScrollPane jScrollPane1 = new SkinnedScrollPane(jList); authorizedKeysPanel.add(jScrollPane1); authorizedKeysPanel.add(boxBottom, BorderLayout.SOUTH); add(hostKeyPanel, BorderLayout.NORTH); add(authorizedKeysPanel); } public void setKeyData(SshKeyHolder holder) {<FILL_FUNCTION_BODY>} private String getAuthorizedKeys() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < model.size(); i++) { String item = model.get(i); sb.append(item); sb.append("\n"); } return sb.toString(); } }
this.txtKeyFile.setText(holder.getRemotePubKeyFile()); this.txtPubKey.setText(holder.getRemotePublicKey()); this.txtPubKey.setEditable(false); this.model.clear(); if (holder.getRemoteAuthorizedKeys() != null) { for (String line : holder.getRemoteAuthorizedKeys().split("\n")) { if (line.trim().length() > 0) { model.addElement(line); } } }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/keys/SshKeyHolder.java
SshKeyHolder
toString
class SshKeyHolder { private String remotePublicKey; private String localPublicKey; private String remoteAuthorizedKeys; private String remotePubKeyFile; private String localPubKeyFile; public SshKeyHolder(){} public SshKeyHolder(String remotePublicKey, String localPublicKey, String remoteAuthorizedKeys, String remotePubKeyFile, String localPubKeyFile) { this.remotePublicKey = remotePublicKey; this.localPublicKey = localPublicKey; this.remoteAuthorizedKeys = remoteAuthorizedKeys; this.remotePubKeyFile = remotePubKeyFile; this.localPubKeyFile = localPubKeyFile; } public String getLocalPubKeyFile() { return localPubKeyFile; } public void setLocalPubKeyFile(String localPubKeyFile) { this.localPubKeyFile = localPubKeyFile; } public String getRemotePublicKey() { return remotePublicKey; } public void setRemotePublicKey(String remotePublicKey) { this.remotePublicKey = remotePublicKey; } public String getLocalPublicKey() { return localPublicKey; } public void setLocalPublicKey(String localPublicKey) { this.localPublicKey = localPublicKey; } public String getRemoteAuthorizedKeys() { return remoteAuthorizedKeys; } public void setRemoteAuthorizedKeys(String remoteAuthorizedKeys) { this.remoteAuthorizedKeys = remoteAuthorizedKeys; } public String getRemotePubKeyFile() { return remotePubKeyFile; } public void setRemotePubKeyFile(String remotePubKeyFile) { this.remotePubKeyFile = remotePubKeyFile; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "SshKeyHolder{" + "remotePublicKey='" + remotePublicKey + '\'' + ", localPublicKey='" + localPublicKey + '\'' + ", remoteAuthorizedKeys='" + remoteAuthorizedKeys + '\'' + ", remotePubKeyFile='" + remotePubKeyFile + '\'' + ", localPubKeyFile='" + localPubKeyFile + '\'' + '}';
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/nettools/NetworkToolsPage.java
NetworkToolsPage
executeAsync
class NetworkToolsPage extends UtilPageItemView { private JTextArea txtOutput; private DefaultComboBoxModel<String> modelHost, modelPort; private JComboBox<String> cmbHost, cmbPort, cmbDNSTool; private JButton btn1, btn2, btn3, btn4; /** * */ public NetworkToolsPage(SessionContentPanel holder) { super(holder); } @Override protected void createUI() { modelHost = new DefaultComboBoxModel<String>(); modelPort = new DefaultComboBoxModel<String>(); cmbHost = new JComboBox<String>(modelHost); cmbPort = new JComboBox<String>(modelPort); cmbHost.setEditable(true); cmbPort.setEditable(true); cmbDNSTool = new JComboBox<String>(new String[] { "nslookup", "dig", "dig +short", "host", "getent ahostsv4" }); JPanel grid = new JPanel(new GridLayout(1, 4, 10, 10)); grid.setBorder(new EmptyBorder(10, 10, 10, 10)); btn1 = new JButton("Ping"); btn2 = new JButton("Port check"); btn3 = new JButton("Traceroute"); btn4 = new JButton("DNS lookup"); btn1.addActionListener(e -> { if (JOptionPane.showOptionDialog(this, new Object[] { "Host to ping", cmbHost }, "Ping", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) { executeAsync("ping -c 4 " + cmbHost.getSelectedItem()); } }); btn2.addActionListener(e -> { if (JOptionPane.showOptionDialog(this, new Object[] { "Host name", cmbHost, "Port number", cmbPort }, "Port check", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) { executeAsync("bash -c 'test cat</dev/tcp/" + cmbHost.getSelectedItem() + "/" + cmbPort.getSelectedItem() + " && echo \"Port Reachable\" || echo \"Port Not reachable\"'"); } }); btn3.addActionListener(e -> { if (JOptionPane.showOptionDialog(this, new Object[] { "Host name", cmbHost }, "Traceroute", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) { executeAsync("traceroute " + cmbHost.getSelectedItem()); } }); btn4.addActionListener(e -> { if (JOptionPane.showOptionDialog(this, new Object[] { "Host name", cmbHost, "Tool to use", cmbDNSTool }, "DNS lookup", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION) { executeAsync(cmbDNSTool.getSelectedItem() + " " + cmbHost.getSelectedItem()); } }); grid.add(btn1); grid.add(btn2); grid.add(btn3); grid.add(btn4); this.setBorder(new EmptyBorder(5, 5, 5, 5)); this.add(grid, BorderLayout.NORTH); txtOutput = new SkinnedTextArea(); txtOutput.setEditable(false); JScrollPane jsp = new SkinnedScrollPane(txtOutput); jsp.setBorder(new LineBorder(App.SKIN.getDefaultBorderColor())); this.add(jsp); } /** * @param string */ private void executeAsync(String cmd) {<FILL_FUNCTION_BODY>} @Override protected void onComponentVisible() { // TODO Auto-generated method stub } @Override protected void onComponentHide() { // TODO Auto-generated method stub } }
AtomicBoolean stopFlag = new AtomicBoolean(false); holder.disableUi(stopFlag); holder.EXECUTOR.submit(() -> { StringBuilder outText = new StringBuilder(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); if (holder.getRemoteSessionInstance().execBin(cmd, stopFlag, bout, null) == 0) { outText.append( new String(bout.toByteArray(), "utf-8") + "\n"); System.out.println("Command stdout: " + outText); } else { JOptionPane.showMessageDialog(this, "Error executed with errors"); } } catch (Exception e) { e.printStackTrace(); } finally { SwingUtilities.invokeLater(() -> { this.txtOutput.setText(outText.toString()); }); holder.enableUi(); } });
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/portview/SocketTableModel.java
SocketTableModel
getValueAt
class SocketTableModel extends AbstractTableModel { private String columns[] = {"Process", "PID", "Host", "Port"}; private List<SocketEntry> list = new ArrayList<>(); public void addEntry(SocketEntry e) { list.add(e); fireTableDataChanged(); } public void addEntries(List<SocketEntry> entries) { if (entries != null) { list.addAll(entries); fireTableDataChanged(); } } @Override public Class<?> getColumnClass(int columnIndex) { return Object.class; } @Override public int getRowCount() { return list.size(); } @Override public int getColumnCount() { return columns.length; } @Override public String getColumnName(int column) { return columns[column]; } @Override public Object getValueAt(int rowIndex, int columnIndex) {<FILL_FUNCTION_BODY>} public void clear() { list.clear(); } }
SocketEntry e = list.get(rowIndex); switch (columnIndex) { case 0: return e.getApp(); case 1: return e.getPid(); case 2: return e.getHost(); case 3: return e.getPort(); default: return ""; }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/services/ServiceEntry.java
ServiceEntry
toString
class ServiceEntry { private String name; private String unitStatus; private String desc; private String unitFileStatus; public ServiceEntry(String name, String unitStatus, String desc, String unitFileStatus) { this.name = name; this.unitStatus = unitStatus; this.desc = desc; this.unitFileStatus = unitFileStatus; } public ServiceEntry() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUnitStatus() { return unitStatus; } public void setUnitStatus(String unitStatus) { this.unitStatus = unitStatus; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getUnitFileStatus() { return unitFileStatus; } public void setUnitFileStatus(String unitFileStatus) { this.unitFileStatus = unitFileStatus; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "ServiceEntry{" + "name='" + name + '\'' + ", unitStatus='" + unitStatus + '\'' + ", desc='" + desc + '\'' + ", unitFileStatus='" + unitFileStatus + '\'' + '}';
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/services/ServiceTableCellRenderer.java
ServiceTableCellRenderer
getTableCellRendererComponent
class ServiceTableCellRenderer extends JLabel implements TableCellRenderer { public ServiceTableCellRenderer() { setText("HHH"); setBorder(new EmptyBorder(5, 5, 5, 5)); setOpaque(true); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {<FILL_FUNCTION_BODY>} }
setText(value == null ? "" : value.toString()); setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); return this;
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/services/ServiceTableModel.java
ServiceTableModel
getValueAt
class ServiceTableModel extends AbstractTableModel { private String columns[] = { "Name", "Status", "State", "Description" }; private List<ServiceEntry> list = new ArrayList<>(); public void addEntry(ServiceEntry e) { list.add(e); fireTableDataChanged(); } public void addEntries(List<ServiceEntry> entries) { if(entries!=null){ list.addAll(entries); fireTableDataChanged(); } } @Override public Class<?> getColumnClass(int columnIndex) { return Object.class; } @Override public int getRowCount() { return list.size(); } @Override public int getColumnCount() { return columns.length; } @Override public String getColumnName(int column) { return columns[column]; } @Override public Object getValueAt(int rowIndex, int columnIndex) {<FILL_FUNCTION_BODY>} public void clear() { list.clear(); } }
ServiceEntry e = list.get(rowIndex); switch (columnIndex) { case 0: return e.getName(); case 1: return e.getUnitFileStatus(); case 2: return e.getUnitStatus(); case 3: return e.getDesc(); default: return ""; }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/sysinfo/SysInfoPanel.java
SysInfoPanel
createUI
class SysInfoPanel extends UtilPageItemView { /** * */ private JTextArea textArea; public SysInfoPanel(SessionContentPanel holder) { super(holder); } @Override protected void createUI() {<FILL_FUNCTION_BODY>} @Override protected void onComponentVisible() { // TODO Auto-generated method stub } @Override protected void onComponentHide() { // TODO Auto-generated method stub } }
textArea = new SkinnedTextArea(); textArea.setFont(new Font(//"DejaVu Sans Mono" "Noto Mono" , Font.PLAIN, 14)); JScrollPane scrollPane = new SkinnedScrollPane(textArea); this.add(scrollPane); AtomicBoolean stopFlag = new AtomicBoolean(false); holder.disableUi(stopFlag); holder.EXECUTOR.submit(() -> { try { StringBuilder output = new StringBuilder(); int ret = holder .getRemoteSessionInstance().exec( ScriptLoader.loadShellScript( "/scripts/linux-sysinfo.sh"), stopFlag, output); if (ret == 0) { SwingUtilities.invokeAndWait(() -> { textArea.setText(output.toString()); textArea.setCaretPosition(0); }); } } catch (Exception e) { e.printStackTrace(); } finally { holder.enableUi(); } });
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/sysload/LineGraph.java
LineGraph
paintComponent
class LineGraph extends JComponent { private static final long serialVersionUID = -8887995348037288952L; private double[] values = new double[0]; private Stroke lineStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); private Stroke gridStroke = new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); private boolean dynamic = false; private String suffix = "%"; private Path2D shape = new Path2D.Double(); private Color bgColor = App.SKIN.getDefaultBackground(), textColor = App.SKIN.getDefaultForeground(), lineColor = new Color(51, 181, 229), gridColor = new Color(62, 68, 81), gridLineColor = App.SKIN.getSelectedTabColor(); @Override protected void paintComponent(Graphics g) {<FILL_FUNCTION_BODY>} private void drawGraph(int width, int height, double den, int count, Graphics2D g2) { shape.reset(); shape.moveTo(width, height); shape.lineTo(0, height); double stepy = (double) height / 4; double stepx = (double) width / count; g2.setColor(gridColor); g2.setStroke(gridStroke); for (int i = 0; i < count + 1; i++) { g2.setColor(gridColor); int y1 = (int) Math.floor((values[i] * height) / den); int x1 = (int) Math.floor(i * stepx); shape.lineTo(x1, height - y1); g2.setColor(gridLineColor); int y = (int) Math.floor(i * stepy); int x = (int) Math.floor(i * stepx); g2.drawLine(0, y, width, y); g2.drawLine(x, 0, x, height); } g2.setColor(lineColor); g2.setStroke(lineStroke); g2.drawRect(0, 0, width, height); g2.draw(shape); g2.setComposite(AlphaComposite.SrcOver.derive(0.4f)); g2.fill(shape); g2.setComposite(AlphaComposite.SrcOver); g2.setColor(gridColor); g2.setStroke(gridStroke); } public double[] getValues() { return values; } public void setValues(double[] values) { this.values = values; repaint(); } public boolean isDynamic() { return dynamic; } public void setDynamic(boolean dynamic) { this.dynamic = dynamic; } public String getSuffix() { return suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }
Graphics2D g2 = (Graphics2D) g.create(); g2.setComposite(AlphaComposite.SrcOver); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(bgColor); g2.fillRect(0, 0, getWidth(), getHeight()); int count = values.length - 1; if (count < 1) return; double den = 100; if (dynamic) { double min = Float.MAX_VALUE; double max = Float.MIN_VALUE; for (int i = 0; i < values.length; i++) { if (values[i] < min) { min = values[i]; } if (values[i] > max) { max = values[i]; } } double extra = ((max - min) * 5) / 100; max += extra; min -= extra; den = max - min; } double denStep = den / 4; int labelWidth = 0; int labelPaddingX = 5; int labelPaddingY = 5; int height = getHeight() - 6; float stepy = height / 4; int ascent = g2.getFontMetrics().getAscent(); g2.setColor(textColor); // for (int i = 0; i < 4; i++) { // if (i == 0 || i % 2 == 0) { // int val = (int) (den - i * denStep); // String label = val + "" + suffix; // int w = g2.getFontMetrics().stringWidth(label); // g2.drawString(label, labelPaddingX + labelWidth - w, (i * stepy + labelPaddingY + ascent)); // } // } int width = getWidth() - 6; int xoff = 2 * labelPaddingX + labelWidth; int yoff = labelPaddingY; g2.translate(3, 3); drawGraph(width, height, den, count, g2); g2.translate(-3, -3); g2.dispose();
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/sysload/LinuxMetrics.java
LinuxMetrics
updateCpu
class LinuxMetrics { private double cpuUsage, memoryUsage, swapUsage; private long totalMemory, usedMemory, totalSwap, usedSwap; private long prev_idle, prev_total; private String OS; public void updateMetrics(RemoteSessionInstance instance) throws Exception { StringBuilder out = new StringBuilder(), err = new StringBuilder(); int ret = instance.exec( "uname; head -1 /proc/stat;grep -E \"MemTotal|MemFree|Cached|SwapTotal|SwapFree\" /proc/meminfo", new AtomicBoolean(), out, err); if (ret != 0) throw new Exception("Error while getting metrics"); // System.out.println(new String(bout.toByteArray())); updateStats(out.toString()); } private void updateStats(String str) { String lines[] = str.split("\n"); OS = lines[0]; String cpuStr = lines[1]; updateCpu(cpuStr); updateMemory(lines); } private void updateCpu(String line) {<FILL_FUNCTION_BODY>} private void updateMemory(String[] lines) { long memTotalK = 0, memFreeK = 0, memCachedK = 0, swapTotalK = 0, swapFreeK = 0, swapCachedK = 0; for (int i = 2; i < lines.length; i++) { String[] arr = lines[i].split("\\s+"); if (arr.length >= 2) { if (arr[0].trim().equals("MemTotal:")) { memTotalK = Long.parseLong(arr[1].trim()); } if (arr[0].trim().equals("Cached:")) { memFreeK = Long.parseLong(arr[1].trim()); } if (arr[0].trim().equals("MemFree:")) { memCachedK = Long.parseLong(arr[1].trim()); } if (arr[0].trim().equals("SwapTotal:")) { swapTotalK = Long.parseLong(arr[1].trim()); } if (arr[0].trim().equals("SwapFree:")) { swapFreeK = Long.parseLong(arr[1].trim()); } } } this.totalMemory = memTotalK * 1024; this.totalSwap = swapTotalK * 1024; long freeMemory = memFreeK * 1024; long freeSwap = swapFreeK * 1024; if (this.totalMemory > 0) { this.usedMemory = this.totalMemory - freeMemory - memCachedK * 1024; this.memoryUsage = ((double) (this.totalMemory - freeMemory - memCachedK * 1024) * 100) / this.totalMemory; } if (this.totalSwap > 0) { this.usedSwap = this.totalSwap - freeSwap - swapCachedK * 1024; this.swapUsage = ((double) (this.totalSwap - freeSwap - swapCachedK * 1024) * 100) / this.totalSwap; } } /** * @return the cpuUsage */ public double getCpuUsage() { return cpuUsage; } /** * @return the memoryUsage */ public double getMemoryUsage() { return memoryUsage; } /** * @return the swapUsage */ public double getSwapUsage() { return swapUsage; } /** * @return the totalMemory */ public long getTotalMemory() { return totalMemory; } /** * @return the usedMemory */ public long getUsedMemory() { return usedMemory; } /** * @return the totalSwap */ public long getTotalSwap() { return totalSwap; } /** * @return the usedSwap */ public long getUsedSwap() { return usedSwap; } /** * @return the oS */ public String getOS() { return OS; } }
String cols[] = line.split("\\s+"); long idle = Long.parseLong(cols[4]); long total = 0; for (int i = 1; i < cols.length; i++) { total += Long.parseLong(cols[i]); } long diff_idle = idle - prev_idle; long diff_total = total - prev_total; this.cpuUsage = (1000 * ((double) diff_total - diff_idle) / diff_total + 5) / 10; this.prev_idle = idle; this.prev_total = total;
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/sysload/SysLoadPage.java
SysLoadPage
createUI
class SysLoadPage extends UtilPageItemView { private SystemLoadPanel systemLoadPanel; private JSpinner spInterval; private AtomicInteger sleepInterval = new AtomicInteger(3); private Timer timer; private LinuxMetrics metrics; private String OS; /** * */ public SysLoadPage(SessionContentPanel holder) { super(holder); } /** * */ private void fetchSystemLoad() { holder.EXECUTOR.submit(() -> { try { if (holder.isSessionClosed()) { SwingUtilities.invokeAndWait(() -> { timer.stop(); }); return; } System.out.println("Getting system metrics"); this.metrics .updateMetrics(this.holder.getRemoteSessionInstance()); if ("Linux".equals(this.metrics.getOS())) { SwingUtilities.invokeAndWait(() -> { // update ui stat systemLoadPanel.setCpuUsage(this.metrics.getCpuUsage()); systemLoadPanel .setMemoryUsage(this.metrics.getMemoryUsage()); systemLoadPanel .setSwapUsage(this.metrics.getSwapUsage()); systemLoadPanel .setTotalMemory(this.metrics.getTotalMemory()); systemLoadPanel .setUsedMemory(this.metrics.getUsedMemory()); systemLoadPanel .setTotalSwap(this.metrics.getTotalSwap()); systemLoadPanel.setUsedSwap(this.metrics.getUsedSwap()); systemLoadPanel.refreshUi(); }); } else { this.OS = this.metrics.getOS(); this.metrics = null; SwingUtilities.invokeLater(() -> { this.timer.stop(); JLabel lblError = new JLabel("Unsupported OS " + this.OS + ", currently only Linux is supported"); lblError.setHorizontalAlignment(JLabel.CENTER); lblError.setVerticalAlignment(JLabel.CENTER); this.remove(systemLoadPanel); this.add(lblError); this.revalidate(); this.repaint(0); }); } } catch (Exception e) { e.printStackTrace(); } }); } private void componentVisible() { startMonitoring(); } private void componentHidden() { stopMonitoring(); } private void startMonitoring() { if (metrics != null) { timer.start(); } } private void stopMonitoring() { timer.stop(); } @Override protected void createUI() {<FILL_FUNCTION_BODY>} @Override protected void onComponentVisible() { componentVisible(); } @Override protected void onComponentHide() { componentHidden(); } }
spInterval = new JSpinner(new SpinnerNumberModel(100, 1, 100, 1)); spInterval.setValue(sleepInterval.get()); spInterval.setMaximumSize(spInterval.getPreferredSize()); spInterval.addChangeListener(e -> { int interval = (Integer) spInterval.getValue(); System.out.println("New interval: " + interval); this.sleepInterval.set(interval); timer.stop(); timer.setDelay(this.sleepInterval.get() * 1000); timer.start(); // this.t.interrupt(); }); systemLoadPanel = new SystemLoadPanel(); Box topPanel = Box.createHorizontalBox(); // topPanel.setOpaque(true); // topPanel.setBackground(new Color(240, 240, 240)); // topPanel.setBorder(new CompoundBorder( // new MatteBorder(0, 0, 1, 0, App.SKIN.getDefaultBorderColor()), // new EmptyBorder(5, 10, 5, 10))); topPanel.setBorder(new EmptyBorder(5, 10, 5, 10)); JLabel titleLabel = new JLabel("System Monitor"); titleLabel.setFont(new Font(Font.DIALOG, Font.PLAIN, 18)); topPanel.add(titleLabel); topPanel.add(Box.createHorizontalGlue()); topPanel.add(new JLabel("Refresh interval")); topPanel.add(Box.createHorizontalStrut(5)); topPanel.add(spInterval); topPanel.add(Box.createHorizontalStrut(5)); topPanel.add(new JLabel("Sec")); this.add(topPanel, BorderLayout.NORTH); this.add(systemLoadPanel); timer = new Timer(this.sleepInterval.get() * 1000, e -> { fetchSystemLoad(); }); timer.setInitialDelay(0); timer.setCoalesce(true); metrics = new LinuxMetrics();
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/session/utilpage/sysload/SystemLoadPanel.java
SystemLoadPanel
setCpuUsage
class SystemLoadPanel extends JPanel { private LineGraph cpuGraph, memGraph, swpGraph; private double cpuStats[] = new double[10]; private double memStats[] = new double[10]; private double swpStats[] = new double[10]; private long totalMemory, usedMemory, totalSwap, usedSwap; private double cpuUsage, memoryUsage, swapUsage; private JLabel cpuLabel, memoryLabel, swapLabel; public SystemLoadPanel() { super(new BorderLayout(5, 5)); setBorder(new EmptyBorder(10, 10, 10, 10)); setMinimumSize(new Dimension(200, 100)); setPreferredSize(new Dimension(300, 400)); Box b1 = Box.createVerticalBox(); cpuLabel = new JLabel("Cpu usage"); cpuLabel.setBorder(new EmptyBorder(0, 0, 10, 0)); cpuLabel.setAlignmentX(Box.LEFT_ALIGNMENT); b1.add(cpuLabel); cpuGraph = new LineGraph(); cpuGraph.setValues(cpuStats); cpuGraph.setAlignmentX(Box.LEFT_ALIGNMENT); b1.add(cpuGraph); memoryLabel = new JLabel("Memory usage"); memoryLabel.setBorder(new EmptyBorder(20, 0, 10, 0)); memoryLabel.setAlignmentX(Box.LEFT_ALIGNMENT); b1.add(memoryLabel); memGraph = new LineGraph(); memGraph.setValues(memStats); memGraph.setAlignmentX(Box.LEFT_ALIGNMENT); b1.add(memGraph); swapLabel = new JLabel("Swap usage"); swapLabel.setBorder(new EmptyBorder(20, 0, 10, 0)); swapLabel.setAlignmentX(Box.LEFT_ALIGNMENT); b1.add(swapLabel); swpGraph = new LineGraph(); swpGraph.setValues(swpStats); swpGraph.setAlignmentX(Box.LEFT_ALIGNMENT); b1.add(swpGraph); // add(new JLabel("System performance"), BorderLayout.NORTH); add(b1); } public void setCpuUsage(double cpuUsage) {<FILL_FUNCTION_BODY>} public void setMemoryUsage(double memoryUsage) { this.memoryUsage = memoryUsage; if (this.memoryUsage != 0) { System.arraycopy(memStats, 1, memStats, 0, memStats.length - 1); memStats[memStats.length - 1] = memoryUsage; } } public void setSwapUsage(double swapUsage) { this.swapUsage = swapUsage; if (this.swapUsage != 0) { System.arraycopy(swpStats, 1, swpStats, 0, swpStats.length - 1); swpStats[swpStats.length - 1] = swapUsage; } } public void setTotalMemory(long totalMemory) { this.totalMemory = totalMemory; } public void setUsedMemory(long usedMemory) { this.usedMemory = usedMemory; } public void setTotalSwap(long totalSwap) { this.totalSwap = totalSwap; } public void setUsedSwap(long usedSwap) { this.usedSwap = usedSwap; } public void refreshUi() { this.cpuLabel .setText(String.format("Cpu usage: %.1f", cpuUsage) + "% "); this.memoryLabel.setText(String.format("Memory usage: %.1f", memoryUsage) + "%" + (totalMemory != 0 ? (", (Total: " + FormatUtils .humanReadableByteCount(totalMemory, true) + ", Used: " + FormatUtils.humanReadableByteCount(usedMemory, true) + ")") : "")); this.swapLabel.setText(String.format("Swap usage: %.1f", swapUsage) + "% " + (totalSwap != 0 ? (", ( Total: " + FormatUtils.humanReadableByteCount(totalSwap, true) + ", Used: " + FormatUtils .humanReadableByteCount(usedSwap, true) + ")") : "")); this.revalidate(); this.repaint(); } }
this.cpuUsage = cpuUsage; if (this.cpuUsage != 0) { System.arraycopy(cpuStats, 1, cpuStats, 0, cpuStats.length - 1); cpuStats[cpuStats.length - 1] = cpuUsage; }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/settings/ColorSelectorButton.java
ColorSelectorButton
mouseClicked
class ColorSelectorButton extends JLabel { /** * */ private Color color; public ColorSelectorButton() { setBorder(new CompoundBorder( new LineBorder(App.SKIN.getDefaultBorderColor()), new CompoundBorder( new MatteBorder(5, 5, 5, 5, App.SKIN.getSelectedTabColor()), new LineBorder(App.SKIN.getDefaultBorderColor())))); setOpaque(true); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) {<FILL_FUNCTION_BODY>} }); } @Override public Dimension getPreferredSize() { return new Dimension(50, 30); } @Override public Dimension getMaximumSize() { return getPreferredSize(); } @Override public Dimension getMinimumSize() { return getPreferredSize(); } /** * @return the color */ public Color getColor() { return color; } /** * @param color the color to set */ public void setColor(Color color) { this.setBackground(color); this.color = color; } }
Color color = JColorChooser.showDialog(null, "Select color", getColor()); if (color != null) { setColor(color); }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/components/settings/FontItemRenderer.java
FontItemRenderer
getListCellRendererComponent
class FontItemRenderer extends JLabel implements ListCellRenderer<String> { /** * */ public FontItemRenderer() { setOpaque(true); } @Override public Component getListCellRendererComponent(JList<? extends String> list, String value, int index, boolean isSelected, boolean cellHasFocus) {<FILL_FUNCTION_BODY>} }
System.out.println("Creating font in renderer: " + value); Font font = FontUtils.loadTerminalFont(value).deriveFont(Font.PLAIN, 14); setFont(font); setText(FontUtils.TERMINAL_FONTS.get(value)); setBackground(isSelected ? App.SKIN.getAddressBarSelectionBackground() : App.SKIN.getSelectedTabColor()); setForeground(isSelected ? App.SKIN.getDefaultSelectionForeground() : App.SKIN.getDefaultForeground()); return this;
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/laf/AppSkinDark.java
AppSkinDark
initDefaultsDark
class AppSkinDark extends AppSkin { /** * */ public AppSkinDark() { initDefaultsDark(); } private void initDefaultsDark() {<FILL_FUNCTION_BODY>} }
Color selectionColor = new Color(3, 155, 229); Color controlColor = new Color(40, 44, 52); Color textColor = new Color(230, 230, 230); Color selectedTextColor = new Color(230, 230, 230); Color infoTextColor = new Color(180, 180, 180); Color borderColor = new Color(24, 26, 31); Color treeTextColor = new Color(75 + 20, 83 + 20, 98 + 20); Color scrollbarColor = new Color(75, 83, 98); Color scrollbarRolloverColor = new Color(75 + 20, 83 + 20, 98 + 20); Color textFieldColor = new Color(40 + 10, 44 + 10, 52 + 10); Color buttonGradient1 = new Color(57, 62, 74); Color buttonGradient2 = new Color(55 - 10, 61 - 10, 72 - 10); Color buttonGradient3 = new Color(57 + 20, 62 + 20, 74 + 20); Color buttonGradient4 = new Color(57 + 10, 62 + 10, 74 + 10); Color buttonGradient5 = new Color(57 - 20, 62 - 20, 74 - 20); Color buttonGradient6 = new Color(57 - 10, 62 - 10, 74 - 10); this.defaults.put("nimbusBase", controlColor); this.defaults.put("nimbusSelection", selectionColor); this.defaults.put("textBackground", selectionColor); this.defaults.put("textHighlight", selectionColor); this.defaults.put("desktop", selectionColor); this.defaults.put("nimbusFocus", selectionColor); this.defaults.put("ArrowButton.foreground", textColor); this.defaults.put("nimbusSelectionBackground", selectionColor); this.defaults.put("nimbusSelectedText", selectedTextColor); this.defaults.put("control", controlColor); this.defaults.put("nimbusBorder", borderColor); this.defaults.put("Table.alternateRowColor", controlColor); this.defaults.put("nimbusLightBackground", textFieldColor); this.defaults.put("tabSelectionBackground", scrollbarColor); this.defaults.put("Table.background", buttonGradient6); this.defaults.put("Table[Enabled+Selected].textForeground", selectedTextColor); // this.defaults.put("scrollbar", buttonGradient4); // this.defaults.put("scrollbar-hot", buttonGradient3); this.defaults.put("text", textColor); this.defaults.put("menuText", textColor); this.defaults.put("controlText", textColor); this.defaults.put("textForeground", textColor); this.defaults.put("infoText", infoTextColor); this.defaults.put("List.foreground", textColor); this.defaults.put("List.background", controlColor); this.defaults.put("List[Disabled].textForeground", selectedTextColor); this.defaults.put("List[Selected].textBackground", selectionColor); this.defaults.put("Label.foreground", textColor); this.defaults.put("Tree.background", textFieldColor); this.defaults.put("Tree.textForeground", treeTextColor); this.defaults.put("scrollbar", scrollbarColor); this.defaults.put("scrollbar-hot", scrollbarRolloverColor); this.defaults.put("button.normalGradient1", buttonGradient1); this.defaults.put("button.normalGradient2", buttonGradient2); this.defaults.put("button.hotGradient1", buttonGradient3); this.defaults.put("button.hotGradient2", buttonGradient4); this.defaults.put("button.pressedGradient1", buttonGradient5); this.defaults.put("button.pressedGradient2", buttonGradient6); this.defaults.put("TextField.background", textFieldColor); this.defaults.put("FormattedTextField.background", textFieldColor); this.defaults.put("PasswordField.background", textFieldColor); createSkinnedButton(this.defaults); createTextFieldSkin(this.defaults); createSpinnerSkin(this.defaults); createComboBoxSkin(this.defaults); createTreeSkin(this.defaults); createTableHeaderSkin(this.defaults); createPopupMenuSkin(this.defaults); createCheckboxSkin(this.defaults); createRadioButtonSkin(this.defaults); createTooltipSkin(this.defaults); createSkinnedToggleButton(this.defaults); createProgressBarSkin(this.defaults); this.defaults.put("ScrollBarUI", CustomScrollBarUI.class.getName());
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/laf/AppSkinLight.java
AppSkinLight
initDefaultsLight
class AppSkinLight extends AppSkin { /** * */ public AppSkinLight() { initDefaultsLight(); } private void initDefaultsLight() {<FILL_FUNCTION_BODY>} }
Color selectionColor = new Color(3, 155, 229); Color controlColor = Color.WHITE; Color textColor = new Color(60, 60, 60); Color selectedTextColor = new Color(250, 250, 250); Color infoTextColor = new Color(80, 80, 80); Color borderColor = new Color(230, 230, 230); Color treeTextColor = new Color(150, 150, 150); Color scrollbarColor = new Color(200, 200, 200); Color scrollbarRolloverColor = new Color(230, 230, 230); Color textFieldColor = new Color(250, 250, 250); Color buttonGradient1 = new Color(250, 250, 250); Color buttonGradient2 = new Color(240, 240, 240); Color buttonGradient3 = new Color(245, 245, 245); Color buttonGradient4 = new Color(235, 235, 235); Color buttonGradient5 = new Color(230, 230, 230); Color buttonGradient6 = new Color(220, 220, 220); this.defaults.put("nimbusBase", controlColor); this.defaults.put("nimbusSelection", selectionColor); this.defaults.put("textBackground", selectionColor); this.defaults.put("textHighlight", selectionColor); this.defaults.put("desktop", selectionColor); this.defaults.put("nimbusFocus", selectionColor); this.defaults.put("ArrowButton.foreground", textColor); this.defaults.put("nimbusSelectionBackground", selectionColor); this.defaults.put("nimbusSelectedText", selectedTextColor); this.defaults.put("control", controlColor); this.defaults.put("nimbusBorder", borderColor); this.defaults.put("nimbusLightBackground", controlColor); this.defaults.put("Table.alternateRowColor", controlColor); this.defaults.put("tabSelectionBackground", scrollbarColor); this.defaults.put("Table.background", buttonGradient1); this.defaults.put("Table[Enabled+Selected].textForeground", selectedTextColor); this.defaults.put("text", textColor); this.defaults.put("menuText", textColor); this.defaults.put("controlText", textColor); this.defaults.put("textForeground", textColor); this.defaults.put("infoText", infoTextColor); this.defaults.put("List.foreground", textColor); this.defaults.put("List.background", controlColor); this.defaults.put("List[Disabled].textForeground", selectedTextColor); this.defaults.put("List[Selected].textBackground", selectionColor); this.defaults.put("Label.foreground", textColor); this.defaults.put("Tree.background", textFieldColor); this.defaults.put("Tree.textForeground", treeTextColor); this.defaults.put("scrollbar", scrollbarColor); this.defaults.put("scrollbar-hot", scrollbarRolloverColor); this.defaults.put("button.normalGradient1", buttonGradient1); this.defaults.put("button.normalGradient2", buttonGradient2); this.defaults.put("button.hotGradient1", buttonGradient3); this.defaults.put("button.hotGradient2", buttonGradient4); this.defaults.put("button.pressedGradient1", buttonGradient5); this.defaults.put("button.pressedGradient2", buttonGradient6); this.defaults.put("TextField.background", textFieldColor); this.defaults.put("FormattedTextField.background", textFieldColor); this.defaults.put("PasswordField.background", textFieldColor); createSkinnedButton(this.defaults); createTextFieldSkin(this.defaults); createSpinnerSkin(this.defaults); createComboBoxSkin(this.defaults); createTreeSkin(this.defaults); createTableHeaderSkin(this.defaults); createPopupMenuSkin(this.defaults); createCheckboxSkin(this.defaults); createRadioButtonSkin(this.defaults); createTooltipSkin(this.defaults); createSkinnedToggleButton(this.defaults); createProgressBarSkin(this.defaults); this.defaults.put("ScrollBarUI", CustomScrollBarUI.class.getName());
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/ui/laf/CustomScrollBarUI.java
CustomScrollBarUI
installUI
class CustomScrollBarUI extends BasicScrollBarUI { private AtomicBoolean hot = new AtomicBoolean(false); public static ComponentUI createUI(JComponent c) { return new CustomScrollBarUI(); } @Override public void installUI(JComponent c) {<FILL_FUNCTION_BODY>} @Override protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { Color color = (Color) c.getClientProperty("ScrollBar.background"); Color cx = color == null ? c.getBackground() : color; g.setColor(cx); g.fillRect(trackBounds.x, trackBounds.y, trackBounds.width, trackBounds.height); } @Override protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) { if (hot.get()) { Color color = (Color) c.getClientProperty("ScrollBar.hotColor"); if (color == null) { g.setColor(UIManager.getColor("scrollbar-hot")); } else { g.setColor(color); } } else { g.setColor(c.getForeground()); } g.fillRect(thumbBounds.x, thumbBounds.y, thumbBounds.width, thumbBounds.height); } @Override protected JButton createDecreaseButton(int orientation) { JButton btn = new JButton(); btn.setMaximumSize(new Dimension(0, 0)); btn.setPreferredSize(new Dimension(0, 0)); return btn; } @Override protected JButton createIncreaseButton(int orientation) { JButton btn = new JButton(); btn.setMaximumSize(new Dimension(0, 0)); btn.setPreferredSize(new Dimension(0, 0)); return btn; } /** * @return the trackColor */ public Color getTrackColor() { return trackColor; } /** * @param trackColor the trackColor to set */ public void setTrackColor(Color trackColor) { this.trackColor = trackColor; } }
super.installUI(c); c.setForeground(UIManager.getColor("scrollbar")); c.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { hot.set(true); c.repaint(); } @Override public void mouseExited(MouseEvent e) { hot.set(false); c.repaint(); } });
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/updater/CertificateValidator.java
CertificateValidator
checkServerTrusted
class CertificateValidator { public static synchronized final void registerCertificateHook() { SSLContext sslContext = null; try { try { sslContext = SSLContext.getInstance("TLS"); } catch (Exception e) { e.printStackTrace(); sslContext = SSLContext.getInstance("SSL"); } TrustManager[] trustAllCerts = new TrustManager[] { new X509ExtendedTrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {<FILL_FUNCTION_BODY>} @Override public X509Certificate[] getAcceptedIssuers() { // TODO Auto-generated method stub return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { try { for (X509Certificate cert : chain) { //System.out.println("checking certificate:- " + cert); cert.checkValidity(); } } catch (CertificateException e) { e.printStackTrace(); if (!confirmCert()) { throw e; } } } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { try { for (X509Certificate cert : chain) { //System.out.println("checking certificate::- " + cert); cert.checkValidity(); } } catch (CertificateException e) { e.printStackTrace(); if (!confirmCert()) { throw e; } } } } }; sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } } private static boolean confirmCert() { return JOptionPane.showConfirmDialog(null, "Update-check\nTrust server certificate?") == JOptionPane.YES_OPTION; } }
try { for (X509Certificate cert : chain) { //System.out.println("checking certificate: " + cert); cert.checkValidity(); } } catch (CertificateException e) { e.printStackTrace(); if (!confirmCert()) { throw e; } }
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/updater/UpdateChecker.java
UpdateChecker
isNewUpdateAvailable
class UpdateChecker { public static final String UPDATE_URL = "https://api.github.com/repos/subhra74/snowflake/releases/latest"; static { CertificateValidator.registerCertificateHook(); } public static boolean isNewUpdateAvailable() {<FILL_FUNCTION_BODY>} }
try { ProxySearch proxySearch = ProxySearch.getDefaultProxySearch(); ProxySelector myProxySelector = proxySearch.getProxySelector(); ProxySelector.setDefault(myProxySelector); System.out.println("Checking for url"); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); VersionEntry latestRelease = objectMapper.readValue(new URL(UPDATE_URL).openStream(), new TypeReference<VersionEntry>() { }); System.out.println("Latest release: " + latestRelease); return latestRelease.compareTo(App.VERSION) > 0; } catch (Exception e) { e.printStackTrace(); } return false;
subhra74_snowflake
snowflake/muon-app/src/main/java/muon/app/updater/VersionEntry.java
VersionEntry
getNumericValue
class VersionEntry implements Comparable<VersionEntry> { private String tag_name; public VersionEntry() { // TODO Auto-generated constructor stub } public VersionEntry(String tag_name) { this.tag_name = tag_name; } @Override public int compareTo(VersionEntry o) { int v1 = getNumericValue(); int v2 = o.getNumericValue(); return v1 - v2; } public final int getNumericValue() {<FILL_FUNCTION_BODY>} public String getTag_name() { return tag_name; } public void setTag_name(String tag_name) { this.tag_name = tag_name; } @Override public String toString() { return "VersionEntry [tag_name=" + tag_name + " value=" + getNumericValue() + "]"; } }
String arr[] = tag_name.substring(1).split("\\."); int value = 0; int multiplier = 1; for (int i = arr.length - 1; i >= 0; i--) { value += Integer.parseInt(arr[i]) * multiplier; multiplier *= 10; } return value;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/CollectionHelper.java
CollectionHelper
arrayList
class CollectionHelper { public static final class Dict<K, V> extends HashMap<K, V> { public Dict<K, V> putItem(K k, V v) { super.put(k, v); return this; } public V getItem(K k) { return super.get(k); } public V getItem(K k, V v) { V v1 = super.get(k); return v1 == null ? v : v1; } } public static final class OrderedDict<K, V> extends LinkedHashMap<K, V> { public OrderedDict<K, V> putItem(K k, V v) { super.put(k, v); return this; } public V getItem(K k) { return super.get(k); } public V getItem(K k, V v) { V v1 = super.get(k); return v1 == null ? v : v1; } } @SafeVarargs public static final <E> List<E> arrayList(E... args) {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") public static final <T> T[] toArray(Collection<T> collection) { return collection.toArray((T[]) new Object[0]); } }
List<E> list = new ArrayList<>(); for (E arg : args) { list.add(arg); } return list;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/FileIconUtil.java
FileIconUtil
getIconForType
class FileIconUtil { public static String getIconForType(FileInfo ent) {<FILL_FUNCTION_BODY>} }
if (ent.getType() == FileType.Directory || ent.getType() == FileType.DirLink) { return FontAwesomeContants.FA_FOLDER; } String name = ent.getName().toLowerCase(Locale.ENGLISH); if (name.endsWith(".zip") || name.endsWith(".tar") || name.endsWith(".tgz") || name.endsWith(".gz") || name.endsWith(".bz2") || name.endsWith(".tbz2") || name.endsWith(".tbz") || name.endsWith(".txz") || name.endsWith(".xz")) { return FontAwesomeContants.FA_FILE_ARCHIVE_O; } else if (name.endsWith(".mp3") || name.endsWith(".aac") || name.endsWith(".mp2") || name.endsWith(".wav") || name.endsWith(".flac") || name.endsWith(".mpa") || name.endsWith(".m4a")) { return FontAwesomeContants.FA_FILE_AUDIO_O; } else if (name.endsWith(".c") || name.endsWith(".js") || name.endsWith(".cpp") || name.endsWith(".java") || name.endsWith(".cs") || name.endsWith(".py") || name.endsWith(".pl") || name.endsWith(".rb") || name.endsWith(".sql") || name.endsWith(".go") || name.endsWith(".ksh") || name.endsWith(".css") || name.endsWith(".scss") || name.endsWith(".html") || name.endsWith(".htm") || name.endsWith(".ts")) { return FontAwesomeContants.FA_FILE_CODE_O; } else if (name.endsWith(".xls") || name.endsWith(".xlsx")) { return FontAwesomeContants.FA_FILE_EXCEL_O; } else if (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png") || name.endsWith(".ico") || name.endsWith(".gif") || name.endsWith(".svg")) { return FontAwesomeContants.FA_FILE_IMAGE_O; } else if (name.endsWith(".mp4") || name.endsWith(".mkv") || name.endsWith(".m4v") || name.endsWith(".avi")) { return FontAwesomeContants.FA_FILE_VIDEO_O; } else if (name.endsWith(".pdf")) { return FontAwesomeContants.FA_FILE_PDF_O; } else if (name.endsWith(".ppt") || name.endsWith(".pptx")) { return FontAwesomeContants.FA_FILE_POWERPOINT_O; } else if (name.endsWith(".doc") || name.endsWith(".docx")) { return FontAwesomeContants.FA_FILE_WORD_O; } return FontAwesomeContants.FA_FILE;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/FontUtils.java
FontUtils
loadTerminalFont
class FontUtils { public static final Map<String, String> TERMINAL_FONTS = new CollectionHelper.OrderedDict<String, String>() .putItem("DejaVuSansMono", "DejaVu Sans Mono").putItem("FiraCode-Regular", "Fira Code Regular") .putItem("Inconsolata-Regular", "Inconsolata Regular").putItem("NotoMono-Regular", "Noto Mono"); public static Font loadFont(String path) { try (InputStream is = AppSkin.class.getResourceAsStream(path)) { Font font = Font.createFont(Font.TRUETYPE_FONT, is); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); System.out.println("Font loaded: " + font.getFontName() + " of family: " + font.getFamily()); return font.deriveFont(Font.PLAIN, 12.0f); } catch (Exception e) { e.printStackTrace(); } return null; } public static Font loadTerminalFont(String name) {<FILL_FUNCTION_BODY>} }
System.out.println("Loading font: "+name); try (InputStream is = AppSkin.class.getResourceAsStream(String.format("/fonts/terminal/%s.ttf", name))) { Font font = Font.createFont(Font.TRUETYPE_FONT, is); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); ge.registerFont(font); System.out.println("Font loaded: " + font.getFontName() + " of family: " + font.getFamily()); return font.deriveFont(Font.PLAIN, 12.0f); } catch (Exception e) { e.printStackTrace(); } return null;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/FormatUtils.java
FormatUtils
humanReadableByteCount
class FormatUtils { public static String humanReadableByteCount(long bytes, boolean si) {<FILL_FUNCTION_BODY>} public static final String formatDate(LocalDateTime dateTime) { return dateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a")); } }
int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %s", bytes / Math.pow(unit, exp), pre);
subhra74_snowflake
snowflake/muon-app/src/main/java/util/LayoutUtilities.java
LayoutUtilities
equalizeSize
class LayoutUtilities { public static void equalizeSize(Component... components) {<FILL_FUNCTION_BODY>} }
int maxWidth = 0, maxHeight = 0; for (Component item : components) { Dimension dim = item.getPreferredSize(); if (maxWidth <= dim.width) { maxWidth = dim.width; } if (maxHeight <= dim.height) { maxHeight = dim.height; } } Dimension dimMax = new Dimension(maxWidth, maxHeight); for (Component item : components) { item.setPreferredSize(dimMax); item.setMinimumSize(dimMax); item.setMaximumSize(dimMax); }
subhra74_snowflake
snowflake/muon-app/src/main/java/util/OptionPaneUtils.java
OptionPaneUtils
showInputDialog
class OptionPaneUtils { public static synchronized int showOptionDialog(Component owner, Object[] components, String title) { return JOptionPane.showOptionDialog(owner, components, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null); } public static synchronized String showInputDialog(Component owner, String text, String title) { return showInputDialog(owner, text, null, title); } public static synchronized String showInputDialog(Component owner, String text, String initialText, String title) {<FILL_FUNCTION_BODY>} }
JTextField txt = new SkinnedTextField(30); if (initialText != null) { txt.setText(initialText); } if (JOptionPane.showOptionDialog(owner, new Object[] { text, txt }, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, null) == JOptionPane.OK_OPTION && txt.getText().length() > 0) { return txt.getText(); } return null;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/PathUtils.java
PathUtils
isSamePath
class PathUtils { public static String combineUnix(String path1, String path2) { return combine(path1, path2, "/"); } public static String combineWin(String path1, String path2) { return combine(path1, path2, "\\"); } public static String combine(String path1, String path2, String separator) { if (path2.startsWith(separator)) { path2 = path2.substring(1); } if (!path1.endsWith(separator)) { return path1 + separator + path2; } else { return path1 + path2; } } public static String getFileName(String file) { if (file.endsWith("/") || file.endsWith("\\")) { file = file.substring(0, file.length() - 1); } int index1 = file.lastIndexOf('/'); int index2 = file.lastIndexOf('\\'); int index = index1 > index2 ? index1 : index2; if (index >= 0) { return file.substring(index + 1); } return file; } public static String getParent(String file) { if (file.endsWith("/") || file.endsWith("\\")) { file = file.substring(0, file.length() - 1); } if (file.length() == 0) { return null; } int index1 = file.lastIndexOf('/'); int index2 = file.lastIndexOf('\\'); int index = index1 > index2 ? index1 : index2; if (index >= 0) { return file.substring(0, index + 1); } return file; } public static boolean isSamePath(String path1, String path2) {<FILL_FUNCTION_BODY>} }
if (path1 == null && path2 == null) { return true; } if (path1 == null) { return false; } return (path1.equals(path2) || (path1 + "/").equals(path2) || (path1 + "\\").equals(path2));
subhra74_snowflake
snowflake/muon-app/src/main/java/util/RegUtil.java
RegUtil
regGetStr
class RegUtil { public static String regGetStr(WinReg.HKEY hkey, String key, String value) {<FILL_FUNCTION_BODY>} public static int regGetInt(WinReg.HKEY hkey, String key, String value) { try { return Advapi32Util.registryGetIntValue(hkey, key, value); } catch (Exception e) { //e.printStackTrace(); } return 0; } }
try { return Advapi32Util.registryGetStringValue(hkey, key, value); } catch (Exception e) { //e.printStackTrace(); } return null;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/ScriptLoader.java
ScriptLoader
loadShellScript
class ScriptLoader { public static synchronized String loadShellScript(String path) {<FILL_FUNCTION_BODY>} }
try { StringBuilder sb = new StringBuilder(); try (BufferedReader r = new BufferedReader(new InputStreamReader( ScriptLoader.class.getResourceAsStream(path)))) { while (true) { String s = r.readLine(); if (s == null) { break; } sb.append(s + "\n"); } } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } return null;
subhra74_snowflake
snowflake/muon-app/src/main/java/util/Win32DragHandler.java
Win32DragHandler
listenForDrop
class Win32DragHandler { private FileMonitor fileMonitor = new W32FileMonitor(); public synchronized void listenForDrop(String keyToListen, Consumer<File> callback) {<FILL_FUNCTION_BODY>} public synchronized void dispose() { System.out.println("File watcher disposed"); this.fileMonitor.dispose(); } // public final static synchronized void initFSWatcher() { // // FileMonitor fileMonitor = new W32FileMonitor(); // fileMonitor.addFileListener(e -> { // System.out.println(e.getFile()); // }); // FileSystemView fsv = FileSystemView.getFileSystemView(); // for (File drive : File.listRoots()) { // if (fsv.isDrive(drive)) { // try { // System.out.println("Adding to watch: " + drive.getAbsolutePath()); // fileMonitor.addWatch(drive, W32FileMonitor.FILE_RENAMED, true); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // } }
FileSystemView fsv = FileSystemView.getFileSystemView(); for (File drive : File.listRoots()) { if (fsv.isDrive(drive)) { try { System.out.println("Adding to watch: " + drive.getAbsolutePath()); fileMonitor.addWatch(drive, W32FileMonitor.FILE_RENAMED | W32FileMonitor.FILE_CREATED, true); } catch (IOException e) { e.printStackTrace(); } } } fileMonitor.addFileListener(e -> { File file = e.getFile(); System.err.println(file); if (file.getName().startsWith(keyToListen)) { callback.accept(file); } });
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ArrayTerminalDataStream.java
ArrayTerminalDataStream
pushChar
class ArrayTerminalDataStream implements TerminalDataStream { protected char[] myBuf; protected int myOffset; protected int myLength; public ArrayTerminalDataStream(char[] buf, int offset, int length) { myBuf = buf; myOffset = offset; myLength = length; } public ArrayTerminalDataStream(char[] buf) { this(buf, 0, buf.length); } public char getChar() throws IOException { if (myLength == 0) { throw new EOF(); } myLength--; return myBuf[myOffset++]; } public void pushChar(final char c) throws EOF {<FILL_FUNCTION_BODY>} public String readNonControlCharacters(int maxChars) throws IOException { String nonControlCharacters = CharUtils.getNonControlCharacters(maxChars, myBuf, myOffset, myLength); myOffset += nonControlCharacters.length(); myLength -= nonControlCharacters.length(); return nonControlCharacters; } public void pushBackBuffer(final char[] bytes, final int length) throws EOF { for (int i = length - 1; i >= 0; i--) { pushChar(bytes[i]); } } }
if (myOffset == 0) { // Pushed back too many... shift it up to the end. char[] newBuf; if (myBuf.length - myLength == 0) { newBuf = new char[myBuf.length + 1]; } else { newBuf = myBuf; } myOffset = newBuf.length - myLength; System.arraycopy(myBuf, 0, newBuf, myOffset, myLength); myBuf = newBuf; } myLength++; myBuf[--myOffset] = c;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/DataStreamIteratingEmulator.java
DataStreamIteratingEmulator
next
class DataStreamIteratingEmulator implements Emulator { protected final TerminalDataStream myDataStream; protected final Terminal myTerminal; private boolean myEof = false; public DataStreamIteratingEmulator(TerminalDataStream dataStream, Terminal terminal) { myDataStream = dataStream; myTerminal = terminal; } @Override public boolean hasNext() { return !myEof; } @Override public void resetEof() { myEof = false; } @Override public void next() throws IOException {<FILL_FUNCTION_BODY>} protected abstract void processChar(char ch, Terminal terminal) throws IOException; }
try { char b = myDataStream.getChar(); processChar(b, myTerminal); } catch (TerminalDataStream.EOF e) { myEof = true; }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/DefaultTerminalCopyPasteHandler.java
DefaultTerminalCopyPasteHandler
getContents
class DefaultTerminalCopyPasteHandler implements TerminalCopyPasteHandler, ClipboardOwner { private static final Logger LOG = Logger.getLogger(DefaultTerminalCopyPasteHandler.class); @Override public void setContents( String text, boolean useSystemSelectionClipboardIfAvailable) { if (useSystemSelectionClipboardIfAvailable) { Clipboard systemSelectionClipboard = getSystemSelectionClipboard(); if (systemSelectionClipboard != null) { setClipboardContents(new StringSelection(text), systemSelectionClipboard); return; } } setSystemClipboardContents(text); } @Override public String getContents(boolean useSystemSelectionClipboardIfAvailable) {<FILL_FUNCTION_BODY>} @SuppressWarnings("WeakerAccess") protected void setSystemClipboardContents( String text) { setClipboardContents(new StringSelection(text), getSystemClipboard()); } private String getSystemClipboardContents() { return getClipboardContents(getSystemClipboard()); } private void setClipboardContents( Transferable contents, Clipboard clipboard) { if (clipboard != null) { try { clipboard.setContents(contents, this); } catch (IllegalStateException e) { logException("Cannot set contents", e); } } } private String getClipboardContents( Clipboard clipboard) { if (clipboard != null) { try { return (String) clipboard.getData(DataFlavor.stringFlavor); } catch (Exception e) { logException("Cannot get clipboard contents", e); } } return null; } private static Clipboard getSystemClipboard() { try { return Toolkit.getDefaultToolkit().getSystemClipboard(); } catch (IllegalStateException e) { logException("Cannot get system clipboard", e); return null; } } private static Clipboard getSystemSelectionClipboard() { try { return Toolkit.getDefaultToolkit().getSystemSelection(); } catch (IllegalStateException e) { logException("Cannot get system selection clipboard", e); return null; } } private static void logException( String message, Exception e) { if (UIUtil.isWindows && e instanceof IllegalStateException) { LOG.debug(message, e); } else { LOG.warn(message, e); } } @Override public void lostOwnership(Clipboard clipboard, Transferable contents) { } }
if (useSystemSelectionClipboardIfAvailable) { Clipboard systemSelectionClipboard = getSystemSelectionClipboard(); if (systemSelectionClipboard != null) { return getClipboardContents(systemSelectionClipboard); } } return getSystemClipboardContents();
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/HyperlinkStyle.java
HyperlinkStyle
build
class HyperlinkStyle extends TextStyle implements Runnable { private final LinkInfo myLinkInfo; private final TextStyle myHighlightStyle; private final TextStyle myPrevTextStyle; private final HighlightMode myHighlightMode; public HyperlinkStyle( TextStyle prevTextStyle, LinkInfo hyperlinkInfo) { this(prevTextStyle.getForeground(), prevTextStyle.getBackground(), hyperlinkInfo, HighlightMode.HOVER, prevTextStyle); } public HyperlinkStyle( TerminalColor foreground, TerminalColor background, LinkInfo hyperlinkInfo, HighlightMode mode, TextStyle prevTextStyle) { this(false, foreground, background, hyperlinkInfo, mode, prevTextStyle); } private HyperlinkStyle(boolean keepColors, TerminalColor foreground, TerminalColor background, LinkInfo hyperlinkInfo, HighlightMode mode, TextStyle prevTextStyle) { super(keepColors ? foreground : null, keepColors ? background : null); myHighlightStyle = new TextStyle.Builder() .setBackground(background) .setForeground(foreground) .setOption(Option.UNDERLINED, true) .build(); myLinkInfo = hyperlinkInfo; myHighlightMode = mode; myPrevTextStyle = prevTextStyle; } public TextStyle getPrevTextStyle() { return myPrevTextStyle; } @Override public void run() { myLinkInfo.navigate(); } public TextStyle getHighlightStyle() { return myHighlightStyle; } public LinkInfo getLinkInfo() { return myLinkInfo; } public HighlightMode getHighlightMode() { return myHighlightMode; } @Override public Builder toBuilder() { return new Builder(this); } public enum HighlightMode { ALWAYS, NEVER, HOVER } public static class Builder extends TextStyle.Builder { private LinkInfo myLinkInfo; private TextStyle myHighlightStyle; private TextStyle myPrevTextStyle; private HighlightMode myHighlightMode; private Builder( HyperlinkStyle style) { myLinkInfo = style.myLinkInfo; myHighlightStyle = style.myHighlightStyle; myPrevTextStyle = style.myPrevTextStyle; myHighlightMode = style.myHighlightMode; } public HyperlinkStyle build() { return build(false); } public HyperlinkStyle build(boolean keepColors) {<FILL_FUNCTION_BODY>} } }
TerminalColor foreground = myHighlightStyle.getForeground(); TerminalColor background = myHighlightStyle.getBackground(); if (keepColors) { TextStyle style = super.build(); foreground = style.getForeground() != null ? style.getForeground() : myHighlightStyle.getForeground(); background = style.getBackground() != null ? style.getBackground() : myHighlightStyle.getBackground(); } return new HyperlinkStyle(keepColors, foreground, background, myLinkInfo, myHighlightMode, myPrevTextStyle);
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ProcessTtyConnector.java
ProcessTtyConnector
close
class ProcessTtyConnector implements TtyConnector { protected final InputStream myInputStream; protected final OutputStream myOutputStream; protected final InputStreamReader myReader; protected Charset myCharset; private Dimension myPendingTermSize; private Dimension myPendingPixelSize; private Process myProcess; public ProcessTtyConnector( Process process, Charset charset) { myOutputStream = process.getOutputStream(); myCharset = charset; myInputStream = process.getInputStream(); myReader = new InputStreamReader(myInputStream, charset); myProcess = process; } public Process getProcess() { return myProcess; } @Override public void resize(Dimension termSize, Dimension pixelSize) { setPendingTermSize(termSize); setPendingPixelSize(pixelSize); if (isConnected()) { resizeImmediately(); setPendingTermSize(null); setPendingPixelSize(null); } } protected abstract void resizeImmediately(); @Override public abstract String getName(); public int read(char[] buf, int offset, int length) throws IOException { return myReader.read(buf, offset, length); //return myInputStream.read(buf, offset, length); } public void write(byte[] bytes) throws IOException { myOutputStream.write(bytes); myOutputStream.flush(); } @Override public abstract boolean isConnected(); @Override public void write(String string) throws IOException { write(string.getBytes(myCharset)); } protected void setPendingTermSize(Dimension pendingTermSize) { this.myPendingTermSize = pendingTermSize; } protected void setPendingPixelSize(Dimension pendingPixelSize) { this.myPendingPixelSize = pendingPixelSize; } protected Dimension getPendingTermSize() { return myPendingTermSize; } protected Dimension getPendingPixelSize() { return myPendingPixelSize; } @Override public boolean init(Questioner q) { return isConnected(); } @Override public void close() {<FILL_FUNCTION_BODY>} @Override public int waitFor() throws InterruptedException { return myProcess.waitFor(); } }
myProcess.destroy(); try { myOutputStream.close(); } catch (IOException ignored) { } try { myInputStream.close(); } catch (IOException ignored) { }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/SubstringFinder.java
SubstringFinder
nextChar
class SubstringFinder { private final String myPattern; private final int myPatternHash; private int myCurrentHash; private int myCurrentLength; private final ArrayList<TextToken> myTokens = new ArrayList<>(); private int myFirstIndex; private int myPower = 0; private final FindResult myResult = new FindResult(); private boolean myIgnoreCase; public SubstringFinder(String pattern, boolean ignoreCase) { myIgnoreCase = ignoreCase; myPattern = ignoreCase ? pattern.toLowerCase() : pattern; myPatternHash = myPattern.hashCode(); } public void nextChar(int x, int y, CharBuffer characters, int index) {<FILL_FUNCTION_BODY>} private int charHash(char c) { return myIgnoreCase ? Character.toLowerCase(c) : c; } private int hashCodeForChar(char charAt) { return myPower * charHash(charAt); } public FindResult getResult() { return myResult; } public static class FindResult { private final List<FindItem> items = new ArrayList<>(); private final Map<CharBuffer, List<Pair<Integer, Integer>>> ranges = new HashMap<CharBuffer, List<Pair<Integer, Integer>>>(); private int currentFindItem = 0; public List<Pair<Integer, Integer>> getRanges(CharBuffer characters) { return ranges.get(characters); } public static class FindItem { final ArrayList<TextToken> tokens; final int firstIndex; final int lastIndex; // index in the result list final int index; private FindItem(ArrayList<TextToken> tokens, int firstIndex, int lastIndex, int index) { this.tokens = new ArrayList<>(tokens); this.firstIndex = firstIndex; this.lastIndex = lastIndex; this.index = index; } // public String getText() { StringBuilder b = new StringBuilder(); if (tokens.size() > 1) { Pair<Integer, Integer> range = Pair.create(firstIndex, tokens.get(0).buf.length()); b.append(tokens.get(0).buf.subBuffer(range)); } else { Pair<Integer, Integer> range = Pair.create(firstIndex, lastIndex + 1); b.append(tokens.get(0).buf.subBuffer(range)); } for (int i = 1; i < tokens.size() - 1; i++) { b.append(tokens.get(i).buf); } if (tokens.size() > 1) { Pair<Integer, Integer> range = Pair.create(0, lastIndex + 1); b.append( tokens.get(tokens.size() - 1).buf.subBuffer(range)); } return b.toString(); } @Override public String toString() { return getText(); } // index in the result list public int getIndex() { return index; } public Point getStart() { return new Point(tokens.get(0).x + firstIndex, tokens.get(0).y); } public Point getEnd() { return new Point(tokens.get(tokens.size() - 1).x + lastIndex, tokens.get(tokens.size() - 1).y); } } public void patternMatched(ArrayList<TextToken> tokens, int firstIndex, int lastIndex) { if (tokens.size() > 1) { Pair<Integer, Integer> range = Pair.create(firstIndex, tokens.get(0).buf.length()); put(tokens.get(0).buf, range); } else { Pair<Integer, Integer> range = Pair.create(firstIndex, lastIndex + 1); put(tokens.get(0).buf, range); } for (int i = 1; i < tokens.size() - 1; i++) { put(tokens.get(i).buf, Pair.create(0, tokens.get(i).buf.length())); } if (tokens.size() > 1) { Pair<Integer, Integer> range = Pair.create(0, lastIndex + 1); put(tokens.get(tokens.size() - 1).buf, range); } items.add(new FindItem(tokens, firstIndex, lastIndex, items.size() + 1)); } private void put(CharBuffer characters, Pair<Integer, Integer> range) { if (ranges.containsKey(characters)) { ranges.get(characters).add(range); } else { ArrayList<Pair<Integer, Integer>> list = new ArrayList<>(); list.add(range); ranges.put(characters, list); } } public List<FindItem> getItems() { return items; } public FindItem prevFindItem() { if (items.isEmpty()) { return null; } currentFindItem++; currentFindItem %= items.size(); return items.get(currentFindItem); } public FindItem nextFindItem() { if (items.isEmpty()) { return null; } currentFindItem--; // modulo can be negative in Java: add items.size() to ensure // positive currentFindItem = (currentFindItem + items.size()) % items.size(); return items.get(currentFindItem); } } private static class TextToken { final CharBuffer buf; final int x; final int y; private TextToken(int x, int y, CharBuffer buf) { this.x = x; this.y = y; this.buf = buf; } } }
if (myTokens.size() == 0 || myTokens.get(myTokens.size() - 1).buf != characters) { myTokens.add(new TextToken(x, y, characters)); } if (myCurrentLength == myPattern.length()) { myCurrentHash -= hashCodeForChar( myTokens.get(0).buf.charAt(myFirstIndex)); if (myFirstIndex + 1 == myTokens.get(0).buf.length()) { myFirstIndex = 0; myTokens.remove(0); } else { myFirstIndex += 1; } } else { myCurrentLength += 1; if (myPower == 0) { myPower = 1; } else { myPower *= 31; } } myCurrentHash = 31 * myCurrentHash + charHash(characters.charAt(index)); if (myCurrentLength == myPattern.length() && myCurrentHash == myPatternHash) { FindResult.FindItem item = new FindResult.FindItem(myTokens, myFirstIndex, index, -1); String itemText = item.getText(); if (myPattern .equals(myIgnoreCase ? itemText.toLowerCase() : itemText)) { myResult.patternMatched(myTokens, myFirstIndex, index); myCurrentHash = 0; myCurrentLength = 0; myPower = 0; myTokens.clear(); if (index + 1 < characters.length()) { myFirstIndex = index + 1; myTokens.add(new TextToken(x, y, characters)); } else { myFirstIndex = 0; } } }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/TerminalColor.java
TerminalColor
equals
class TerminalColor { public static final TerminalColor BLACK = index(0); public static final TerminalColor WHITE = index(15); private int myColorIndex; private Color myColor; public TerminalColor(int index) { myColorIndex = index; myColor = null; } public TerminalColor(int r, int g, int b) { myColorIndex = -1; myColor = new Color(r, g, b); } public static TerminalColor index(int index) { return new TerminalColor(index); } public static TerminalColor rgb(int r, int g, int b) { return new TerminalColor(r, g, b); } public boolean isIndexed() { return myColorIndex != -1; } public Color toAwtColor() { if (isIndexed()) { throw new IllegalArgumentException("Color is indexed color so a palette is needed"); } return myColor; } public int getIndex() { return myColorIndex; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return myColor != null ? myColor.hashCode() : myColorIndex; } public static TerminalColor awt( Color color) { if (color == null) { return null; } return rgb(color.getRed(), color.getGreen(), color.getBlue()); } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TerminalColor that = (TerminalColor) o; if (isIndexed()) { if (!that.isIndexed()) return false; if (myColorIndex != that.myColorIndex) return false; } else { if (that.isIndexed()) { return false; } return myColor.equals(that.myColor); } return true;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/TerminalStarter.java
TerminalStarter
close
class TerminalStarter implements TerminalOutputStream { private static final Logger LOG = Logger.getLogger(TerminalStarter.class); private final Emulator myEmulator; private final Terminal myTerminal; private final TerminalDataStream myDataStream; private final TtyConnector myTtyConnector; private final ExecutorService myEmulatorExecutor = Executors.newSingleThreadExecutor(); public TerminalStarter(final Terminal terminal, final TtyConnector ttyConnector, TerminalDataStream dataStream) { myTtyConnector = ttyConnector; //can be implemented - just recreate channel and that's it myDataStream = dataStream; myTerminal = terminal; myTerminal.setTerminalOutput(this); myEmulator = createEmulator(myDataStream, terminal); } protected JediEmulator createEmulator(TerminalDataStream dataStream, Terminal terminal) { return new JediEmulator(dataStream, terminal); } private void execute(Runnable runnable) { if (!myEmulatorExecutor.isShutdown()) { myEmulatorExecutor.execute(runnable); } } public void start() { try { while (!Thread.currentThread().isInterrupted() && myEmulator.hasNext()) { myEmulator.next(); } } catch (final InterruptedIOException e) { LOG.info("Terminal exiting"); } catch (final Exception e) { if (!myTtyConnector.isConnected()) { myTerminal.disconnected(); return; } LOG.error("Caught exception in terminal thread", e); } } public byte[] getCode(final int key, final int modifiers) { return myTerminal.getCodeForKey(key, modifiers); } public void postResize(final Dimension dimension, final RequestOrigin origin) { execute(() -> resizeTerminal(myTerminal, myTtyConnector, dimension, origin)); } /** * Resizes terminal and tty connector, should be called on a pooled thread. */ public static void resizeTerminal( Terminal terminal, TtyConnector ttyConnector, Dimension terminalDimension, RequestOrigin origin) { Dimension pixelSize; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (terminal) { pixelSize = terminal.resize(terminalDimension, origin); } ttyConnector.resize(terminalDimension, pixelSize); } @Override public void sendBytes(final byte[] bytes) { execute(() -> { try { myTtyConnector.write(bytes); } catch (IOException e) { throw new RuntimeException(e); } }); } @Override public void sendString(final String string) { execute(() -> { try { myTtyConnector.write(string); } catch (IOException e) { throw new RuntimeException(e); } }); } public void close() {<FILL_FUNCTION_BODY>} }
execute(() -> { try { myTtyConnector.close(); } catch (Exception e) { LOG.error("Error closing terminal", e); } finally { myEmulatorExecutor.shutdown(); } });
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/TextStyle.java
TextStyle
getCanonicalStyle
class TextStyle { private static final EnumSet<Option> NO_OPTIONS = EnumSet.noneOf(Option.class); public static final TextStyle EMPTY = new TextStyle(); private static final WeakHashMap<TextStyle, WeakReference<TextStyle>> styles = new WeakHashMap<>(); private final TerminalColor myForeground; private final TerminalColor myBackground; private final EnumSet<Option> myOptions; public TextStyle() { this(null, null, NO_OPTIONS); } public TextStyle( TerminalColor foreground, TerminalColor background) { this(foreground, background, NO_OPTIONS); } public TextStyle( TerminalColor foreground, TerminalColor background, EnumSet<Option> options) { myForeground = foreground; myBackground = background; myOptions = options.clone(); } public static TextStyle getCanonicalStyle(TextStyle currentStyle) {<FILL_FUNCTION_BODY>} public TerminalColor getForeground() { return myForeground; } public TerminalColor getBackground() { return myBackground; } public TextStyle createEmptyWithColors() { return new TextStyle(myForeground, myBackground); } public int getId() { return hashCode(); } public boolean hasOption(final Option option) { return myOptions.contains(option); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TextStyle textStyle = (TextStyle) o; return Objects.equals(myForeground, textStyle.myForeground) && Objects.equals(myBackground, textStyle.myBackground) && myOptions.equals(textStyle.myOptions); } @Override public int hashCode() { return Objects.hash(myForeground, myBackground, myOptions); } public TerminalColor getBackgroundForRun() { return myOptions.contains(Option.INVERSE) ? myForeground : myBackground; } public TerminalColor getForegroundForRun() { return myOptions.contains(Option.INVERSE) ? myBackground : myForeground; } public Builder toBuilder() { return new Builder(this); } public enum Option { BOLD, ITALIC, BLINK, DIM, INVERSE, UNDERLINED, HIDDEN; private void set( EnumSet<Option> options, boolean val) { if (val) { options.add(this); } else { options.remove(this); } } } public static class Builder { private TerminalColor myForeground; private TerminalColor myBackground; private EnumSet<Option> myOptions; public Builder( TextStyle textStyle) { myForeground = textStyle.myForeground; myBackground = textStyle.myBackground; myOptions = textStyle.myOptions.clone(); } public Builder() { myForeground = null; myBackground = null; myOptions = EnumSet.noneOf(Option.class); } public Builder setForeground( TerminalColor foreground) { myForeground = foreground; return this; } public Builder setBackground( TerminalColor background) { myBackground = background; return this; } public Builder setOption( Option option, boolean val) { option.set(myOptions, val); return this; } public TextStyle build() { return new TextStyle(myForeground, myBackground, myOptions); } } }
if (currentStyle instanceof HyperlinkStyle) { return currentStyle; } final WeakReference<TextStyle> canonRef = styles.get(currentStyle); if (canonRef != null) { final TextStyle canonStyle = canonRef.get(); if (canonStyle != null) { return canonStyle; } } styles.put(currentStyle, new WeakReference<>(currentStyle)); return currentStyle;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/TtyBasedArrayDataStream.java
TtyBasedArrayDataStream
fillBuf
class TtyBasedArrayDataStream extends ArrayTerminalDataStream { private TtyConnector myTtyConnector; public TtyBasedArrayDataStream(final TtyConnector ttyConnector) { super(new char[1024], 0, 0); myTtyConnector = ttyConnector; } private void fillBuf() throws IOException {<FILL_FUNCTION_BODY>} public char getChar() throws IOException { if (myLength == 0) { fillBuf(); } return super.getChar(); } public String readNonControlCharacters(int maxChars) throws IOException { if (myLength == 0) { fillBuf(); } return super.readNonControlCharacters(maxChars); } }
myOffset = 0; myLength = myTtyConnector.read(myBuf, myOffset, myBuf.length); if (myLength <= 0) { myLength = 0; throw new EOF(); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/TtyConnectorWaitFor.java
TtyConnectorWaitFor
run
class TtyConnectorWaitFor { private static final Logger LOG = Logger.getLogger(TtyConnectorWaitFor.class); private final Future<?> myWaitForThreadFuture; private final BlockingQueue<Predicate<Integer>> myTerminationCallback = new ArrayBlockingQueue<Predicate<Integer>>(1); public void detach() { myWaitForThreadFuture.cancel(true); } public TtyConnectorWaitFor(final TtyConnector ttyConnector, final ExecutorService executor) { myWaitForThreadFuture = executor.submit(new Runnable() { @Override public void run() {<FILL_FUNCTION_BODY>} }); } public void setTerminationCallback(Predicate<Integer> r) { myTerminationCallback.offer(r); } }
int exitCode = 0; try { while (true) { try { exitCode = ttyConnector.waitFor(); break; } catch (InterruptedException e) { LOG.debug(e); } } } finally { try { if (!myWaitForThreadFuture.isCancelled()) { myTerminationCallback.take().test(exitCode); } } catch (InterruptedException e) { LOG.info(e); } }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/debug/BufferPanel.java
BufferPanel
update
class BufferPanel extends JPanel { public BufferPanel(final TerminalSession terminal) { super(new BorderLayout()); final JTextArea area = new JTextArea(); area.setEditable(false); add(area, BorderLayout.NORTH); final DebugBufferType[] choices = DebugBufferType.values(); final JComboBox chooser = new JComboBox(choices); add(chooser, BorderLayout.NORTH); area.setFont(Font.decode("Monospaced-14")); add(new JScrollPane(area), BorderLayout.CENTER); class Updater implements ActionListener, ItemListener { private String myLastUpdate = ""; void update() {<FILL_FUNCTION_BODY>} public void actionPerformed(final ActionEvent e) { update(); } public void itemStateChanged(final ItemEvent e) { update(); } } final Updater up = new Updater(); chooser.addItemListener(up); final Timer timer = new Timer(1000, up); timer.setRepeats(true); timer.start(); } }
final DebugBufferType type = (DebugBufferType) chooser.getSelectedItem(); final String text = terminal.getBufferText(type); if (!text.equals(myLastUpdate)) { area.setText(text); myLastUpdate = text; }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/debug/ControlSequenceVisualizer.java
ControlSequenceVisualizer
readOutput
class ControlSequenceVisualizer { private static final Logger LOG = Logger.getLogger(ControlSequenceVisualizer.class); private File myTempFile; public ControlSequenceVisualizer() { myTempFile = null; try { myTempFile = File.createTempFile("jeditermData", ".txt"); myTempFile.deleteOnExit(); } catch (IOException e) { throw new IllegalStateException(e); } } public String getVisualizedString(List<char[]> chunks) { try { writeChunksToFile(chunks); return readOutput("teseq " + myTempFile.getAbsolutePath()); } catch (IOException e) { return "Control sequence visualizer teseq is not installed.\nSee http://www.gnu.org/software/teseq/\nNow printing characters as is:\n\n" + joinChunks(chunks); } } private static String joinChunks(List<char[]> chunks) { StringBuilder sb = new StringBuilder(); for (char[] ch : chunks) { sb.append(ch); } return sb.toString(); } private void writeChunksToFile(List<char[]> chunks) throws IOException { OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(myTempFile, false)); try { for (char[] data : chunks) { stream.write(data, 0, data.length); } } finally { stream.close(); } } public String readOutput(String command) throws IOException {<FILL_FUNCTION_BODY>} }
String line; Process process = Runtime.getRuntime().exec(command); Reader inStreamReader = new InputStreamReader(process.getInputStream()); BufferedReader in = new BufferedReader(inStreamReader); StringBuilder sb = new StringBuilder(); int i = 0; String lastNum = null; while ((line = in.readLine()) != null) { if (!line.startsWith("&") && !line.startsWith("\"")) { lastNum = String.format("%3d ", i++); sb.append(lastNum); } else { if (lastNum != null) { sb.append(CharBuffer.allocate(lastNum.length()).toString().replace('\0', ' ')); } } sb.append(line); sb.append("\n"); } in.close(); return sb.toString();
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/emulator/ControlSequence.java
ControlSequence
appendToBuffer
class ControlSequence { private int myArgc; private int[] myArgv; private char myFinalChar; private ArrayList<Character> myUnhandledChars; private boolean myStartsWithQuestionMark = false; // true when CSI ? private boolean myStartsWithMoreMark = false; // true when CSI > private final StringBuilder mySequenceString = new StringBuilder(); ControlSequence(final TerminalDataStream channel) throws IOException { myArgv = new int[5]; myArgc = 0; readControlSequence(channel); } private void readControlSequence(final TerminalDataStream channel) throws IOException { myArgc = 0; // Read integer arguments int digit = 0; int seenDigit = 0; int pos = -1; while (true) { final char b = channel.getChar(); mySequenceString.append(b); pos++; if (b == '?' && pos == 0) { myStartsWithQuestionMark = true; } else if (b == '>' && pos == 0) { myStartsWithMoreMark = true; } else if (b == ';') { if (digit > 0) { myArgc++; if (myArgc == myArgv.length) { int[] replacement = new int[myArgv.length * 2]; System.arraycopy(myArgv, 0, replacement, 0, myArgv.length); myArgv = replacement; } myArgv[myArgc] = 0; digit = 0; } } else if ('0' <= b && b <= '9') { myArgv[myArgc] = myArgv[myArgc] * 10 + b - '0'; digit++; seenDigit = 1; } else if (':' <= b && b <= '?') { addUnhandled(b); } else if (0x40 <= b && b <= 0x7E) { myFinalChar = b; break; } else { addUnhandled(b); } } myArgc += seenDigit; } private void addUnhandled(final char b) { if (myUnhandledChars == null) { myUnhandledChars = new ArrayList<>(); } myUnhandledChars.add(b); } public boolean pushBackReordered(final TerminalDataStream channel) throws IOException { if (myUnhandledChars == null) return false; final char[] bytes = new char[1024]; // can't be more than the whole buffer... int i = 0; for (final char b : myUnhandledChars) { bytes[i++] = b; } bytes[i++] = (byte)CharUtils.ESC; bytes[i++] = (byte)'['; if (myStartsWithQuestionMark) { bytes[i++] = (byte)'?'; } if (myStartsWithMoreMark) { bytes[i++] = (byte)'>'; } for (int argi = 0; argi < myArgc; argi++) { if (argi != 0) bytes[i++] = ';'; String s = Integer.toString(myArgv[argi]); for (int j = 0; j < s.length(); j++) { bytes[i++] = s.charAt(j); } } bytes[i++] = myFinalChar; channel.pushBackBuffer(bytes, i); return true; } int getCount() { return myArgc; } final int getArg(final int index, final int defaultValue) { if (index >= myArgc) { return defaultValue; } return myArgv[index]; } public String appendTo(final String str) { StringBuilder sb = new StringBuilder(str); appendToBuffer(sb); return sb.toString(); } public final void appendToBuffer(final StringBuilder sb) {<FILL_FUNCTION_BODY>} @Override public String toString() { StringBuilder sb = new StringBuilder(); appendToBuffer(sb); return sb.toString(); } public char getFinalChar() { return myFinalChar; } public boolean startsWithQuestionMark() { return myStartsWithQuestionMark; } public boolean startsWithMoreMark() { return myStartsWithMoreMark; } public String getSequenceString() { return mySequenceString.toString(); } }
sb.append("ESC["); if (myStartsWithQuestionMark) { sb.append("?"); } if (myStartsWithMoreMark) { sb.append(">"); } String sep = ""; for (int i = 0; i < myArgc; i++) { sb.append(sep); sb.append(myArgv[i]); sep = ";"; } sb.append(myFinalChar); if (myUnhandledChars != null) { sb.append(" Unhandled:"); CharUtils.CharacterType last = CharUtils.CharacterType.NONE; for (final char b : myUnhandledChars) { last = CharUtils.appendChar(sb, last, (char)b); } }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/emulator/SystemCommandSequence.java
SystemCommandSequence
readSystemCommandSequence
class SystemCommandSequence { private final List<Object> myArgs = new ArrayList<>(); private final StringBuilder mySequenceString = new StringBuilder(); public SystemCommandSequence(TerminalDataStream dataStream) throws IOException { readSystemCommandSequence(dataStream); } private void readSystemCommandSequence(TerminalDataStream stream) throws IOException {<FILL_FUNCTION_BODY>} private boolean isEnd(char b) { return b == Ascii.BEL || b == 0x9c || isTwoBytesEnd(b); } private boolean isTwoBytesEnd(char ch) { int len = mySequenceString.length(); return len >= 2 && mySequenceString.charAt(len - 2) == Ascii.ESC && ch == '\\'; } public String getStringAt(int i) { if (i>=myArgs.size()) { return null; } Object val = myArgs.get(i); return val instanceof String ? (String)val : null; } public Integer getIntAt(int i) { if (i>=myArgs.size()) { return null; } Object val = myArgs.get(i); return val instanceof Integer? (Integer)val : null; } public String getSequenceString() { return mySequenceString.toString(); } }
boolean isNumber = true; int number = 0; StringBuilder string = new StringBuilder(); while (true) { final char b = stream.getChar(); mySequenceString.append(b); if (b == ';' || isEnd(b)) { if (isTwoBytesEnd(b)) { string.delete(string.length() - 1, string.length()); } if (isNumber) { myArgs.add(number); } else { myArgs.add(string.toString()); } if (isEnd(b)) { break; } isNumber = true; number = 0; string = new StringBuilder(); } else if (isNumber) { if ('0' <= b && b <= '9') { number = number * 10 + b - '0'; } else { isNumber = false; } string.append(b); } else { string.append(b); } }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/emulator/charset/GraphicSet.java
GraphicSet
map
class GraphicSet { private final int myIndex; // 0..3 private CharacterSet myDesignation; public GraphicSet( int index ) { if ( index < 0 || index > 3 ) { throw new IllegalArgumentException( "Invalid index!" ); } myIndex = index; // The default mapping, based on XTerm... myDesignation = CharacterSet.valueOf( ( index == 1 ) ? '0' : 'B' ); } /** * @return the designation of this graphic set. */ public CharacterSet getDesignation() { return myDesignation; } /** * @return the index of this graphics set. */ public int getIndex() { return myIndex; } /** * Maps a given character index to a concrete character. * * @param original * the original character to map; * @param index * the index of the character to map. * @return the mapped character, or the given original if no mapping could * be made. */ public int map( char original, int index ) {<FILL_FUNCTION_BODY>} /** * Sets the designation of this graphic set. */ public void setDesignation( CharacterSet designation ) { myDesignation = designation; } }
int result = myDesignation.map( index ); if ( result < 0 ) { // No mapping, simply return the given original one... result = original; } return result;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/emulator/charset/GraphicSetState.java
GraphicSetState
getGL
class GraphicSetState { private final GraphicSet[] myGraphicSets; //in-use table graphic left (GL) private GraphicSet myGL; //in-use table graphic right (GR) private GraphicSet myGR; //Override for next char (used by shift-in and shift-out) private GraphicSet myGlOverride; public GraphicSetState() { myGraphicSets = new GraphicSet[4]; for (int i = 0; i < myGraphicSets.length; i++) { myGraphicSets[i] = new GraphicSet(i); } resetState(); } /** * Designates the given graphic set to the character set designator. * * @param graphicSet the graphic set to designate; * @param designator the designator of the character set. */ public void designateGraphicSet( GraphicSet graphicSet, char designator) { graphicSet.setDesignation(CharacterSet.valueOf(designator)); } public void designateGraphicSet(int num, CharacterSet characterSet) { getGraphicSet(num).setDesignation(characterSet); } /** * Returns the (possibly overridden) GL graphic set. */ public GraphicSet getGL() {<FILL_FUNCTION_BODY>} /** * Returns the GR graphic set. */ public GraphicSet getGR() { return myGR; } /** * Returns the current graphic set (one of four). * * @param index the index of the graphic set, 0..3. */ public GraphicSet getGraphicSet(int index) { return myGraphicSets[index % 4]; } /** * Returns the mapping for the given character. * * @param ch the character to map. * @return the mapped character. */ public char map(char ch) { return CharacterSets.getChar(ch, getGL(), getGR()); } /** * Overrides the GL graphic set for the next written character. * * @param index the graphic set index, >= 0 && < 3. */ public void overrideGL(int index) { myGlOverride = getGraphicSet(index); } /** * Resets the state to its initial values. */ public void resetState() { for (int i = 0; i < myGraphicSets.length; i++) { myGraphicSets[i].setDesignation(CharacterSet.valueOf((i == 1) ? '0' : 'B')); } myGL = myGraphicSets[0]; myGR = myGraphicSets[1]; myGlOverride = null; } /** * Selects the graphic set for GL. * * @param index the graphic set index, >= 0 && <= 3. */ public void setGL(int index) { myGL = getGraphicSet(index); } /** * Selects the graphic set for GR. * * @param index the graphic set index, >= 0 && <= 3. */ public void setGR(int index) { myGR = getGraphicSet(index); } public int getGLOverrideIndex() { return myGlOverride != null ? myGlOverride.getIndex() : -1; } }
GraphicSet result = myGL; if (myGlOverride != null) { result = myGlOverride; myGlOverride = null; } return result;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/ChangeWidthOperation.java
ChangeWidthOperation
run
class ChangeWidthOperation { private static final Logger LOG = Logger .getLogger(TerminalTextBuffer.class); private final TerminalTextBuffer myTextBuffer; private final int myNewWidth; private final int myNewHeight; private final Map<Point, Point> myTrackingPoints = new HashMap<>(); private final List<TerminalLine> myAllLines = new ArrayList<>(); private TerminalLine myCurrentLine; private int myCurrentLineLength; ChangeWidthOperation(TerminalTextBuffer textBuffer, int newWidth, int newHeight) { myTextBuffer = textBuffer; myNewWidth = newWidth; myNewHeight = newHeight; } void addPointToTrack(Point original) { myTrackingPoints.put(new Point(original), null); } Point getTrackedPoint(Point original) { Point result = myTrackingPoints.get(new Point(original)); if (result == null) { LOG.warn("Not tracked point: " + original); return original; } return result; } void run() {<FILL_FUNCTION_BODY>} private int getEmptyBottomLineCount() { int result = 0; while (result < myAllLines.size() && myAllLines.get(myAllLines.size() - result - 1).isNul()) { result++; } return result; } private List<Point> findPointsAtY(int y) { List<Point> result = Collections.emptyList(); for (Point key : myTrackingPoints.keySet()) { if (key.y == y) { if (result.isEmpty()) { result = new ArrayList<>(); } result.add(key); } } return result; } private void addLine(TerminalLine line) { if (line.isNul()) { if (myCurrentLine != null) { myCurrentLine = null; myCurrentLineLength = 0; } myAllLines.add(TerminalLine.createEmpty()); return; } line.forEachEntry(entry -> { if (entry.isNul()) { return; } int entryProcessedLength = 0; while (entryProcessedLength < entry.getLength()) { if (myCurrentLine != null && myCurrentLineLength == myNewWidth) { myCurrentLine.setWrapped(true); myCurrentLine = null; myCurrentLineLength = 0; } if (myCurrentLine == null) { myCurrentLine = new TerminalLine(); myCurrentLineLength = 0; myAllLines.add(myCurrentLine); } int len = Math.min(myNewWidth - myCurrentLineLength, entry.getLength() - entryProcessedLength); TerminalLine.TextEntry newEntry = subEntry(entry, entryProcessedLength, len); myCurrentLine.appendEntry(newEntry); myCurrentLineLength += len; entryProcessedLength += len; } }); if (!line.isWrapped()) { myCurrentLine = null; myCurrentLineLength = 0; } } private static TerminalLine.TextEntry subEntry(TerminalLine.TextEntry entry, int startInd, int count) { if (startInd == 0 && count == entry.getLength()) { return entry; } return new TerminalLine.TextEntry(entry.getStyle(), entry.getText().subBuffer(startInd, count)); } }
LinesBuffer historyBuffer = myTextBuffer.getHistoryBufferOrBackup(); for (int i = 0; i < historyBuffer.getLineCount(); i++) { TerminalLine line = historyBuffer.getLine(i); addLine(line); } int screenStartInd = myAllLines.size() - 1; if (myCurrentLine == null || myCurrentLineLength == myNewWidth) { screenStartInd++; } if (!(screenStartInd >= 0)) { throw new IllegalArgumentException( String.format("screenStartInd < 0: %d", screenStartInd)); } // Preconditions.checkState(screenStartInd >= 0, "screenStartInd < 0: // %d", screenStartInd); LinesBuffer screenBuffer = myTextBuffer.getScreenBufferOrBackup(); if (screenBuffer.getLineCount() > myTextBuffer.getHeight()) { LOG.warn("Terminal height < screen buffer line count: " + myTextBuffer.getHeight() + " < " + screenBuffer.getLineCount()); } int oldScreenLineCount = Math.min(screenBuffer.getLineCount(), myTextBuffer.getHeight()); for (int i = 0; i < oldScreenLineCount; i++) { List<Point> points = findPointsAtY(i); for (Point point : points) { int newX = (myCurrentLineLength + point.x) % myNewWidth; int newY = myAllLines.size() + (myCurrentLineLength + point.x) / myNewWidth; if (myCurrentLine != null) { newY--; } myTrackingPoints.put(point, new Point(newX, newY)); } addLine(screenBuffer.getLine(i)); } for (int i = oldScreenLineCount; i < myTextBuffer.getHeight(); i++) { List<Point> points = findPointsAtY(i); for (Point point : points) { int newX = point.x % myNewWidth; int newY = (i - oldScreenLineCount) + myAllLines.size() + point.x / myNewWidth; myTrackingPoints.put(point, new Point(newX, newY)); } } int emptyBottomLineCount = getEmptyBottomLineCount(); screenStartInd = Math.max(screenStartInd, myAllLines.size() - Math.min(myAllLines.size(), myNewHeight) - emptyBottomLineCount); screenStartInd = Math.min(screenStartInd, myAllLines.size() - Math.min(myAllLines.size(), myNewHeight)); historyBuffer.clearAll(); historyBuffer.addLines(myAllLines.subList(0, screenStartInd)); screenBuffer.clearAll(); screenBuffer.addLines(myAllLines.subList(screenStartInd, Math.min(screenStartInd + myNewHeight, myAllLines.size()))); for (Map.Entry<Point, Point> entry : myTrackingPoints.entrySet()) { Point p = entry.getValue(); if (p != null) { p.y -= screenStartInd; } else { p = new Point(entry.getKey()); entry.setValue(p); } p.x = Math.min(myNewWidth, Math.max(0, p.x)); p.y = Math.min(myNewHeight, Math.max(0, p.y)); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/CharBuffer.java
CharBuffer
iterator
class CharBuffer implements Iterable<Character>, CharSequence { public final static CharBuffer EMPTY = new CharBuffer(new char[0], 0, 0); private final char[] myBuf; private final int myStart; private final int myLength; public CharBuffer( char[] buf, int start, int length) { if (start + length > buf.length) { throw new IllegalArgumentException(String.format("Out ouf bounds %d+%d>%d", start, length, buf.length)); } myBuf = buf; myStart = start; myLength = length; if (myLength < 0) { throw new IllegalStateException("Length can't be negative: " + myLength); } if (myStart < 0) { throw new IllegalStateException("Start position can't be negative: " + myStart); } if (myStart + myLength > myBuf.length) { throw new IllegalStateException(String.format("Interval is out of array bounds: %d+%d>%d", myStart, myLength, myBuf.length)); } } public CharBuffer(char c, int count) { this(new char[count], 0, count); assert !CharUtils.isDoubleWidthCharacter(c, false); Arrays.fill(myBuf, c); } public CharBuffer( String str) { this(str.toCharArray(), 0, str.length()); } @Override public Iterator<Character> iterator() {<FILL_FUNCTION_BODY>} public char[] getBuf() { return myBuf; } public int getStart() { return myStart; } public CharBuffer subBuffer(int start, int length) { return new CharBuffer(myBuf, getStart() + start, length); } public CharBuffer subBuffer(Pair<Integer, Integer> range) { return new CharBuffer(myBuf, getStart() + range.first, range.second - range.first); } public boolean isNul() { return myLength > 0 && myBuf[0] == CharUtils.NUL_CHAR; } public void unNullify() { Arrays.fill(myBuf, CharUtils.EMPTY_CHAR); } @Override public int length() { return myLength; } @Override public char charAt(int index) { return myBuf[myStart + index]; } @Override public CharSequence subSequence(int start, int end) { return new CharBuffer(myBuf, myStart + start, end - start); } @Override public String toString() { return new String(myBuf, myStart, myLength); } public CharBuffer clone() { char[] newBuf = Arrays.copyOfRange(myBuf, myStart, myStart + myLength); return new CharBuffer(newBuf, 0, myLength); } }
return new Iterator<Character>() { private int myCurPosition = myStart; @Override public boolean hasNext() { return myCurPosition < myBuf.length && myCurPosition < myStart + myLength; } @Override public Character next() { return myBuf[myCurPosition]; } @Override public void remove() { throw new IllegalStateException("Can't remove from buffer"); } };
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/SelectionUtil.java
SelectionUtil
sortPoints
class SelectionUtil { private static final Logger LOG = Logger.getLogger(SelectionUtil.class); private static final List<Character> SEPARATORS = new ArrayList<Character>(); static { SEPARATORS.add(' '); SEPARATORS.add('\u00A0'); // NO-BREAK SPACE SEPARATORS.add('\t'); SEPARATORS.add('\''); SEPARATORS.add('"'); SEPARATORS.add('$'); SEPARATORS.add('('); SEPARATORS.add(')'); SEPARATORS.add('['); SEPARATORS.add(']'); SEPARATORS.add('{'); SEPARATORS.add('}'); SEPARATORS.add('<'); SEPARATORS.add('>'); } public static List<Character> getDefaultSeparators() { return new ArrayList<Character>(SEPARATORS); } public static Pair<Point, Point> sortPoints(Point a, Point b) {<FILL_FUNCTION_BODY>} public static String getSelectionText(TerminalSelection selection, TerminalTextBuffer terminalTextBuffer) { return getSelectionText(selection.getStart(), selection.getEnd(), terminalTextBuffer); } public static String getSelectionText( Point selectionStart, Point selectionEnd, TerminalTextBuffer terminalTextBuffer) { Pair<Point, Point> pair = sortPoints(selectionStart, selectionEnd); pair.first.y = Math.max(pair.first.y, - terminalTextBuffer.getHistoryLinesCount()); pair = sortPoints(pair.first, pair.second); // previous line may have change the order Point top = pair.first; Point bottom = pair.second; final StringBuilder selectionText = new StringBuilder(); for (int i = top.y; i <= bottom.y; i++) { TerminalLine line = terminalTextBuffer.getLine(i); String text = line.getText(); if (i == top.y) { if (i == bottom.y) { selectionText.append(processForSelection(text.substring(Math.min(text.length(), top.x), Math.min(text.length(), bottom.x)))); } else { selectionText.append(processForSelection(text.substring(Math.min(text.length(), top.x)))); } } else if (i == bottom.y) { selectionText.append(processForSelection(text.substring(0, Math.min(text.length(), bottom.x)))); } else { selectionText.append(processForSelection(line.getText())); } if ((!line.isWrapped() && i < bottom.y) || bottom.x > text.length()) { selectionText.append("\n"); } } return selectionText.toString(); } private static String processForSelection(String text) { if (text.indexOf(CharUtils.DWC) != 0) { // remove dwc second chars StringBuilder sb = new StringBuilder(); for (char c : text.toCharArray()) { if (c != CharUtils.DWC) { sb.append(c); } } return sb.toString(); } else { return text; } } public static Point getPreviousSeparator(Point charCoords, TerminalTextBuffer terminalTextBuffer) { return getPreviousSeparator(charCoords, terminalTextBuffer, SEPARATORS); } public static Point getPreviousSeparator(Point charCoords, TerminalTextBuffer terminalTextBuffer, List<Character> separators) { int x = charCoords.x; int y = charCoords.y; int terminalWidth = terminalTextBuffer.getWidth(); if (separators.contains(terminalTextBuffer.getBuffersCharAt(x, y))) { return new Point(x, y); } String line = terminalTextBuffer.getLine(y).getText(); while (x < line.length() && !separators.contains(line.charAt(x))) { x--; if (x < 0) { if (y <= - terminalTextBuffer.getHistoryLinesCount()) { return new Point(0, y); } y--; x = terminalWidth - 1; line = terminalTextBuffer.getLine(y).getText(); } } x++; if (x >= terminalWidth) { y++; x = 0; } return new Point(x, y); } public static Point getNextSeparator(Point charCoords, TerminalTextBuffer terminalTextBuffer) { return getNextSeparator(charCoords, terminalTextBuffer, SEPARATORS); } public static Point getNextSeparator(Point charCoords, TerminalTextBuffer terminalTextBuffer, List<Character> separators) { int x = charCoords.x; int y = charCoords.y; int terminalWidth = terminalTextBuffer.getWidth(); int terminalHeight = terminalTextBuffer.getHeight(); if (separators.contains(terminalTextBuffer.getBuffersCharAt(x, y))) { return new Point(x, y); } String line = terminalTextBuffer.getLine(y).getText(); while (x < line.length() && !separators.contains(line.charAt(x))) { x++; if (x >= terminalWidth) { if (y >= terminalHeight - 1) { return new Point(terminalWidth - 1, terminalHeight - 1); } y++; x = 0; line = terminalTextBuffer.getLine(y).getText(); } } x--; if (x < 0) { y--; x = terminalWidth - 1; } return new Point(x, y); } }
if (a.y == b.y) { /* same line */ return Pair.create(a.x <= b.x ? a : b, a.x > b.x ? a : b); } else { return Pair.create(a.y < b.y ? a : b, a.y > b.y ? a : b); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/StyleState.java
StyleState
merge
class StyleState { private TextStyle myCurrentStyle = TextStyle.EMPTY; private TextStyle myDefaultStyle = TextStyle.EMPTY; private TextStyle myMergedStyle = null; public StyleState() { } public TextStyle getCurrent() { return TextStyle.getCanonicalStyle(getMergedStyle()); } private static TextStyle merge( TextStyle style, TextStyle defaultStyle) {<FILL_FUNCTION_BODY>} public void reset() { myCurrentStyle = myDefaultStyle; myMergedStyle = null; } public void set(StyleState styleState) { setCurrent(styleState.getCurrent()); } public void setDefaultStyle(TextStyle defaultStyle) { myDefaultStyle = defaultStyle; myMergedStyle = null; } public TerminalColor getBackground() { return getBackground(null); } public TerminalColor getBackground(TerminalColor color) { return color != null ? color : myDefaultStyle.getBackground(); } public TerminalColor getForeground() { return getForeground(null); } public TerminalColor getForeground(TerminalColor color) { return color != null ? color : myDefaultStyle.getForeground(); } public void setCurrent(TextStyle current) { myCurrentStyle = current; myMergedStyle = null; } private TextStyle getMergedStyle() { if (myMergedStyle == null) { myMergedStyle = merge(myCurrentStyle, myDefaultStyle); } return myMergedStyle; } }
TextStyle.Builder builder = style.toBuilder(); if (style.getBackground() == null && defaultStyle.getBackground() != null) { builder.setBackground(defaultStyle.getBackground()); } if (style.getForeground() == null && defaultStyle.getForeground() != null) { builder.setForeground(defaultStyle.getForeground()); } return builder.build();
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/TerminalSelection.java
TerminalSelection
intersect
class TerminalSelection { private final Point myStart; private Point myEnd; public TerminalSelection(Point start) { myStart = start; } public TerminalSelection(Point start, Point end) { myStart = start; myEnd = end; } public Point getStart() { return myStart; } public Point getEnd() { return myEnd; } public void updateEnd(Point end) { myEnd = end; } public Pair<Point, Point> pointsForRun(int width) { Pair<Point, Point> p = SelectionUtil.sortPoints(new Point(myStart), new Point(myEnd)); p.second.x = Math.min(p.second.x + 1, width); return p; } public boolean contains(Point toTest) { return intersects(toTest.x, toTest.y, 1); } public void shiftY(int dy) { myStart.y += dy; myEnd.y += dy; } public boolean intersects(int x, int row, int length) { return null != intersect(x, row, length); } public Pair<Integer, Integer> intersect(int x, int row, int length) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "[x=" + myStart.x + ",y=" + myStart.y + "]" + " -> [x=" + myEnd.x + ",y=" + myEnd.y + "]"; } }
int newX = x; int newLength; Pair<Point, Point> p = SelectionUtil.sortPoints(new Point(myStart), new Point(myEnd)); if (p.first.y == row) { newX = Math.max(x, p.first.x); } if (p.second.y == row) { newLength = Math.min(p.second.x, x + length - 1) - newX + 1; } else { newLength = length - newX + x; } if (newLength<=0 || row < p.first.y || row > p.second.y) { return null; } else return Pair.create(newX, newLength);
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/hyperlinks/LinkResult.java
LinkResult
getItems
class LinkResult { private final LinkResultItem myItem; private List<LinkResultItem> myItemList; public LinkResult( LinkResultItem item) { myItem = item; myItemList = null; } public LinkResult( List<LinkResultItem> itemList) { myItemList = itemList; myItem = null; } public List<LinkResultItem> getItems() {<FILL_FUNCTION_BODY>} }
if (myItemList == null) { myItemList = new ArrayList<>(Arrays.asList(myItem)); } return myItemList;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/model/hyperlinks/TextProcessing.java
TextProcessing
doProcessHyperlinks
class TextProcessing { private static final Logger LOG = Logger.getLogger(TextProcessing.class); private final List<HyperlinkFilter> myHyperlinkFilter; private TextStyle myHyperlinkColor; private HyperlinkStyle.HighlightMode myHighlightMode; private TerminalTextBuffer myTerminalTextBuffer; public TextProcessing( TextStyle hyperlinkColor, HyperlinkStyle.HighlightMode highlightMode) { myHyperlinkColor = hyperlinkColor; myHighlightMode = highlightMode; myHyperlinkFilter = new ArrayList<>(); } public void setTerminalTextBuffer( TerminalTextBuffer terminalTextBuffer) { myTerminalTextBuffer = terminalTextBuffer; } public void processHyperlinks( LinesBuffer buffer, TerminalLine updatedLine) { if (myHyperlinkFilter.isEmpty()) return; doProcessHyperlinks(buffer, updatedLine); } private void doProcessHyperlinks( LinesBuffer buffer, TerminalLine updatedLine) {<FILL_FUNCTION_BODY>} private int findHistoryLineInd( LinesBuffer historyBuffer, TerminalLine line) { int lastLineInd = Math.max(0, historyBuffer.getLineCount() - 200); // check only last lines in history buffer for (int i = historyBuffer.getLineCount() - 1; i >= lastLineInd; i--) { if (historyBuffer.getLine(i) == line) { return i; } } return -1; } private static int findLineInd( LinesBuffer buffer, TerminalLine line) { for (int i = 0; i < buffer.getLineCount(); i++) { TerminalLine l = buffer.getLine(i); if (l == line) { return i; } } return -1; } private String joinLines( LinesBuffer buffer, int startLineInd, int updatedLineInd) { StringBuilder result = new StringBuilder(); for (int i = startLineInd; i <= updatedLineInd; i++) { String text = buffer.getLine(i).getText(); if (i < updatedLineInd && text.length() < myTerminalTextBuffer.getWidth()) { text = text + new CharBuffer(CharUtils.NUL_CHAR, myTerminalTextBuffer.getWidth() - text.length()); } result.append(text); } return result.toString(); } public void addHyperlinkFilter( HyperlinkFilter filter) { myHyperlinkFilter.add(filter); } }
myTerminalTextBuffer.lock(); try { int updatedLineInd = findLineInd(buffer, updatedLine); if (updatedLineInd == -1) { // When lines arrive fast enough, the line might be pushed to the history buffer already. updatedLineInd = findHistoryLineInd(myTerminalTextBuffer.getHistoryBuffer(), updatedLine); if (updatedLineInd == -1) { LOG.debug("Cannot find line for links processing"); return; } buffer = myTerminalTextBuffer.getHistoryBuffer(); } int startLineInd = updatedLineInd; while (startLineInd > 0 && buffer.getLine(startLineInd - 1).isWrapped()) { startLineInd--; } String lineStr = joinLines(buffer, startLineInd, updatedLineInd); for (HyperlinkFilter filter : myHyperlinkFilter) { LinkResult result = filter.apply(lineStr); if (result != null) { for (LinkResultItem item : result.getItems()) { TextStyle style = new HyperlinkStyle(myHyperlinkColor.getForeground(), myHyperlinkColor.getBackground(), item.getLinkInfo(), myHighlightMode, null); if (item.getStartOffset() < 0 || item.getEndOffset() > lineStr.length()) continue; int prevLinesLength = 0; for (int lineInd = startLineInd; lineInd <= updatedLineInd; lineInd++) { int startLineOffset = Math.max(prevLinesLength, item.getStartOffset()); int endLineOffset = Math.min(prevLinesLength + myTerminalTextBuffer.getWidth(), item.getEndOffset()); if (startLineOffset < endLineOffset) { buffer.getLine(lineInd).writeString(startLineOffset - prevLinesLength, new CharBuffer(lineStr.substring(startLineOffset, endLineOffset)), style); } prevLinesLength += myTerminalTextBuffer.getWidth(); } } } } } finally { myTerminalTextBuffer.unlock(); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/AbstractTerminalFrame.java
AbstractTerminalFrame
run
class AbstractTerminalFrame { public static final Logger LOG = Logger.getLogger(AbstractTerminalFrame.class); private JFrame myBufferFrame; private TerminalWidget myTerminal; private AbstractAction myOpenAction = new AbstractAction("New Session") { public void actionPerformed(final ActionEvent e) { openSession(myTerminal); } }; private AbstractAction myShowBuffersAction = new AbstractAction("Show buffers") { public void actionPerformed(final ActionEvent e) { if (myBufferFrame == null) { showBuffers(); } } }; private AbstractAction myDumpDimension = new AbstractAction("Dump terminal dimension") { public void actionPerformed(final ActionEvent e) { LOG.info(myTerminal.getTerminalDisplay().getColumnCount() + "x" + myTerminal.getTerminalDisplay().getRowCount()); } }; private AbstractAction myDumpSelection = new AbstractAction("Dump selection") { public void actionPerformed(final ActionEvent e) { Pair<Point, Point> points = myTerminal.getTerminalDisplay() .getSelection().pointsForRun(myTerminal.getTerminalDisplay().getColumnCount()); LOG.info(myTerminal.getTerminalDisplay().getSelection() + " : '" + SelectionUtil.getSelectionText(points.first, points.second, myTerminal.getCurrentSession().getTerminalTextBuffer()) + "'"); } }; private AbstractAction myDumpCursorPosition = new AbstractAction("Dump cursor position") { public void actionPerformed(final ActionEvent e) { LOG.info(myTerminal.getCurrentSession().getTerminal().getCursorX() + "x" + myTerminal.getCurrentSession().getTerminal().getCursorY()); } }; private AbstractAction myCursor0x0 = new AbstractAction("1x1") { public void actionPerformed(final ActionEvent e) { myTerminal.getCurrentSession().getTerminal().cursorPosition(1, 1); } }; private AbstractAction myCursor10x10 = new AbstractAction("10x10") { public void actionPerformed(final ActionEvent e) { myTerminal.getCurrentSession().getTerminal().cursorPosition(10, 10); } }; private AbstractAction myCursor80x24 = new AbstractAction("80x24") { public void actionPerformed(final ActionEvent e) { myTerminal.getCurrentSession().getTerminal().cursorPosition(80, 24); } }; private JMenuBar getJMenuBar() { final JMenuBar mb = new JMenuBar(); final JMenu m = new JMenu("File"); m.add(myOpenAction); mb.add(m); final JMenu dm = new JMenu("Debug"); JMenu logLevel = new JMenu("Set log level ..."); Level[] levels = new Level[] {Level.ALL, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL, Level.OFF}; for(final Level l : levels) { logLevel.add(new AbstractAction(l.toString()) { @Override public void actionPerformed(ActionEvent e) { Logger.getRootLogger().setLevel(l); } }); } dm.add(logLevel); dm.addSeparator(); dm.add(myShowBuffersAction); dm.addSeparator(); dm.add(myDumpDimension); dm.add(myDumpSelection); dm.add(myDumpCursorPosition); JMenu cursorPosition = new JMenu("Set cursor position ..."); cursorPosition.add(myCursor0x0); cursorPosition.add(myCursor10x10); cursorPosition.add(myCursor80x24); dm.add(cursorPosition); mb.add(dm); return mb; } protected JediTermWidget openSession(TerminalWidget terminal) { if (terminal.canOpenSession()) { return openSession(terminal, createTtyConnector()); } return null; } public JediTermWidget openSession(TerminalWidget terminal, TtyConnector ttyConnector) { JediTermWidget session = terminal.createTerminalSession(ttyConnector); session.start(); return session; } public abstract TtyConnector createTtyConnector(); protected AbstractTerminalFrame() { myTerminal = createTabbedTerminalWidget(); final JFrame frame = new JFrame("JediTerm"); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { System.exit(0); } }); final JMenuBar mb = getJMenuBar(); frame.setJMenuBar(mb); sizeFrameForTerm(frame); frame.getContentPane().add("Center", myTerminal.getComponent()); frame.pack(); frame.setLocationByPlatform(true); frame.setVisible(true); frame.setResizable(true); myTerminal.setTerminalPanelListener(new TerminalPanelListener() { public void onPanelResize(final Dimension pixelDimension, final RequestOrigin origin) { if (origin == RequestOrigin.Remote) { sizeFrameForTerm(frame); } frame.pack(); } @Override public void onSessionChanged(final TerminalSession currentSession) { frame.setTitle(currentSession.getSessionName()); } @Override public void onTitleChanged(String title) { frame.setTitle(myTerminal.getCurrentSession().getSessionName()); } }); openSession(myTerminal); } protected AbstractTabbedTerminalWidget createTabbedTerminalWidget() { return new TabbedTerminalWidget(new DefaultTabbedSettingsProvider(), this::openSession) { @Override public JediTermWidget createInnerTerminalWidget() { return createTerminalWidget(getSettingsProvider()); } }; } protected JediTermWidget createTerminalWidget( TabbedSettingsProvider settingsProvider) { return new JediTermWidget(settingsProvider); } private void sizeFrameForTerm(final JFrame frame) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Dimension d = myTerminal.getPreferredSize(); d.width += frame.getWidth() - frame.getContentPane().getWidth(); d.height += frame.getHeight() - frame.getContentPane().getHeight(); frame.setSize(d); } }); } private void showBuffers() { SwingUtilities.invokeLater(new Runnable() { public void run() {<FILL_FUNCTION_BODY>} }); } }
myBufferFrame = new JFrame("buffers"); final JPanel panel = new BufferPanel(myTerminal.getCurrentSession()); myBufferFrame.getContentPane().add(panel); myBufferFrame.pack(); myBufferFrame.setLocationByPlatform(true); myBufferFrame.setVisible(true); myBufferFrame.setSize(800, 600); myBufferFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { myBufferFrame = null; } });
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/JediTermWidget.java
JediTermWidget
updateLabel
class JediTermWidget extends JPanel implements TerminalSession, TerminalWidget, TerminalActionProvider { private static final Logger LOG = Logger.getLogger(JediTermWidget.class); protected final TerminalPanel myTerminalPanel; protected final JScrollBar myScrollBar; protected final JediTerminal myTerminal; protected final AtomicBoolean mySessionRunning = new AtomicBoolean(); private SearchComponent myFindComponent; private final PreConnectHandler myPreConnectHandler; private TtyConnector myTtyConnector; private TerminalStarter myTerminalStarter; private Thread myEmuThread; protected final SettingsProvider mySettingsProvider; private TerminalActionProvider myNextActionProvider; private JLayeredPane myInnerPanel; private final TextProcessing myTextProcessing; private final List<TerminalWidgetListener> myListeners = new CopyOnWriteArrayList<>(); public JediTermWidget(SettingsProvider settingsProvider) { this(80, 24, settingsProvider); } public JediTermWidget(Dimension dimension, SettingsProvider settingsProvider) { this(dimension.width, dimension.height, settingsProvider); } public JediTermWidget(int columns, int lines, SettingsProvider settingsProvider) { super(new BorderLayout()); mySettingsProvider = settingsProvider; StyleState styleState = createDefaultStyle(); myTextProcessing = new TextProcessing( settingsProvider.getHyperlinkColor(), settingsProvider.getHyperlinkHighlightingMode()); TerminalTextBuffer terminalTextBuffer = new TerminalTextBuffer(columns, lines, styleState, settingsProvider.getBufferMaxLinesCount(), myTextProcessing); myTextProcessing.setTerminalTextBuffer(terminalTextBuffer); myTerminalPanel = createTerminalPanel(mySettingsProvider, styleState, terminalTextBuffer); myTerminal = new JediTerminal(myTerminalPanel, terminalTextBuffer, styleState); myTerminal.setModeEnabled(TerminalMode.AltSendsEscape, mySettingsProvider.altSendsEscape()); myTerminalPanel.addTerminalMouseListener(myTerminal); myTerminalPanel.setNextProvider(this); myTerminalPanel.setCoordAccessor(myTerminal); myPreConnectHandler = createPreConnectHandler(myTerminal); myTerminalPanel.addCustomKeyListener(myPreConnectHandler); myScrollBar = createScrollBar(); myInnerPanel = new JLayeredPane(); myInnerPanel.setFocusable(false); setFocusable(false); myInnerPanel.setLayout(new TerminalLayout()); myInnerPanel.add(myTerminalPanel, TerminalLayout.TERMINAL); myInnerPanel.add(myScrollBar, TerminalLayout.SCROLL); add(myInnerPanel, BorderLayout.CENTER); myScrollBar.setModel(myTerminalPanel.getBoundedRangeModel()); mySessionRunning.set(false); myTerminalPanel.init(); myTerminalPanel.setVisible(true); } protected JScrollBar createScrollBar() { JScrollBar scrollBar = new JScrollBar(); scrollBar.setUI(new FindResultScrollBarUI()); return scrollBar; } protected StyleState createDefaultStyle() { StyleState styleState = new StyleState(); styleState.setDefaultStyle(mySettingsProvider.getDefaultStyle()); return styleState; } protected TerminalPanel createTerminalPanel( SettingsProvider settingsProvider, StyleState styleState, TerminalTextBuffer terminalTextBuffer) { return new TerminalPanel(settingsProvider, terminalTextBuffer, styleState); } protected PreConnectHandler createPreConnectHandler(JediTerminal terminal) { return new PreConnectHandler(terminal); } public TerminalDisplay getTerminalDisplay() { return getTerminalPanel(); } public TerminalPanel getTerminalPanel() { return myTerminalPanel; } public void setTtyConnector(TtyConnector ttyConnector) { myTtyConnector = ttyConnector; myTerminalStarter = createTerminalStarter(myTerminal, myTtyConnector); myTerminalPanel.setTerminalStarter(myTerminalStarter); } protected TerminalStarter createTerminalStarter(JediTerminal terminal, TtyConnector connector) { return new TerminalStarter(terminal, connector, new TtyBasedArrayDataStream(connector)); } @Override public TtyConnector getTtyConnector() { return myTtyConnector; } @Override public Terminal getTerminal() { return myTerminal; } @Override public String getSessionName() { if (myTtyConnector != null) { return myTtyConnector.getName(); } else { return "Session"; } } public void start() { if (!mySessionRunning.get()) { myEmuThread = new Thread(new EmulatorTask()); myEmuThread.start(); } else { LOG.error( "Should not try to start session again at this point... "); } } public void stop() { if (mySessionRunning.get() && myEmuThread != null) { myEmuThread.interrupt(); } } public boolean isSessionRunning() { return mySessionRunning.get(); } public String getBufferText(DebugBufferType type) { return type.getValue(this); } @Override public TerminalTextBuffer getTerminalTextBuffer() { return myTerminalPanel.getTerminalTextBuffer(); } @Override public boolean requestFocusInWindow() { SwingUtilities.invokeLater(new Runnable() { public void run() { myTerminalPanel.requestFocusInWindow(); } }); return super.requestFocusInWindow(); } @Override public void requestFocus() { myTerminalPanel.requestFocus(); } public boolean canOpenSession() { return !isSessionRunning(); } @Override public void setTerminalPanelListener( TerminalPanelListener terminalPanelListener) { myTerminalPanel.setTerminalPanelListener(terminalPanelListener); } @Override public TerminalSession getCurrentSession() { return this; } @Override public JediTermWidget createTerminalSession(TtyConnector ttyConnector) { setTtyConnector(ttyConnector); return this; } @Override public JComponent getComponent() { return this; } @Override public void close() { stop(); if (myTerminalStarter != null) { myTerminalStarter.close(); } myTerminalPanel.dispose(); } @Override public List<TerminalAction> getActions() { Predicate<KeyEvent> p = new Predicate<KeyEvent>() { @Override public boolean test(KeyEvent input) { showFindText(); return true; } }; return new ArrayList<>(Arrays.asList(new TerminalAction("Find", mySettingsProvider.getFindKeyStrokes(), p) .withMnemonicKey(KeyEvent.VK_F))); } private void showFindText() { if (myFindComponent == null) { myFindComponent = createSearchComponent(); final JComponent component = myFindComponent.getComponent(); myInnerPanel.add(component, TerminalLayout.FIND); myInnerPanel.moveToFront(component); myInnerPanel.revalidate(); myInnerPanel.repaint(); component.requestFocus(); myFindComponent.addDocumentChangeListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { textUpdated(); } @Override public void removeUpdate(DocumentEvent e) { textUpdated(); } @Override public void changedUpdate(DocumentEvent e) { textUpdated(); } private void textUpdated() { findText(myFindComponent.getText(), myFindComponent.ignoreCase()); } }); myFindComponent.addIgnoreCaseListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { findText(myFindComponent.getText(), myFindComponent.ignoreCase()); } }); myFindComponent.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) { myInnerPanel.remove(component); myInnerPanel.revalidate(); myInnerPanel.repaint(); myFindComponent = null; myTerminalPanel.setFindResult(null); myTerminalPanel.requestFocusInWindow(); } else if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER || keyEvent.getKeyCode() == KeyEvent.VK_UP) { myFindComponent.nextFindResultItem( myTerminalPanel.selectNextFindResultItem()); } else if (keyEvent.getKeyCode() == KeyEvent.VK_DOWN) { myFindComponent.prevFindResultItem( myTerminalPanel.selectPrevFindResultItem()); } else { super.keyPressed(keyEvent); } } }); } else { myFindComponent.getComponent().requestFocusInWindow(); } } protected SearchComponent createSearchComponent() { return new SearchPanel(); } protected interface SearchComponent { String getText(); boolean ignoreCase(); JComponent getComponent(); void addDocumentChangeListener(DocumentListener listener); void addKeyListener(KeyListener listener); void addIgnoreCaseListener(ItemListener listener); void onResultUpdated(FindResult results); void nextFindResultItem(FindItem selectedItem); void prevFindResultItem(FindItem selectedItem); } private void findText(String text, boolean ignoreCase) { FindResult results = myTerminal.searchInTerminalTextBuffer(text, ignoreCase); myTerminalPanel.setFindResult(results); myFindComponent.onResultUpdated(results); myScrollBar.repaint(); } @Override public TerminalActionProvider getNextProvider() { return myNextActionProvider; } public void setNextProvider(TerminalActionProvider actionProvider) { this.myNextActionProvider = actionProvider; } class EmulatorTask implements Runnable { public void run() { try { mySessionRunning.set(true); Thread.currentThread() .setName("Connector-" + myTtyConnector.getName()); if (myTtyConnector.init(myPreConnectHandler)) { myTerminalPanel.addCustomKeyListener( myTerminalPanel.getTerminalKeyListener()); myTerminalPanel .removeCustomKeyListener(myPreConnectHandler); myTerminalStarter.start(); } } catch (Exception e) { LOG.error("Exception running terminal", e); } finally { try { myTtyConnector.close(); } catch (Exception e) { } mySessionRunning.set(false); TerminalPanelListener terminalPanelListener = myTerminalPanel .getTerminalPanelListener(); if (terminalPanelListener != null) terminalPanelListener.onSessionChanged(getCurrentSession()); for (TerminalWidgetListener listener : myListeners) { listener.allSessionsClosed(JediTermWidget.this); } myTerminalPanel.addCustomKeyListener(myPreConnectHandler); myTerminalPanel.removeCustomKeyListener( myTerminalPanel.getTerminalKeyListener()); } } } public TerminalStarter getTerminalStarter() { return myTerminalStarter; } public class SearchPanel extends JPanel implements SearchComponent { private final JTextField myTextField = new JTextField(); private final JLabel label = new JLabel(); private final JButton prev; private final JButton next; private final JCheckBox ignoreCaseCheckBox = new JCheckBox( "Ignore Case", true); public SearchPanel() { next = createNextButton(); next.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { nextFindResultItem( myTerminalPanel.selectNextFindResultItem()); } }); prev = createPrevButton(); prev.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { prevFindResultItem( myTerminalPanel.selectPrevFindResultItem()); } }); myTextField.setPreferredSize( new Dimension(myTerminalPanel.myCharSize.width * 30, myTerminalPanel.myCharSize.height + 3)); myTextField.setEditable(true); updateLabel(null); add(myTextField); add(ignoreCaseCheckBox); add(label); add(next); add(prev); setOpaque(true); } protected JButton createNextButton() { return new BasicArrowButton(SwingConstants.NORTH); } protected JButton createPrevButton() { return new BasicArrowButton(SwingConstants.SOUTH); } @Override public void nextFindResultItem(FindItem selectedItem) { updateLabel(selectedItem); } @Override public void prevFindResultItem(FindItem selectedItem) { updateLabel(selectedItem); } private void updateLabel(FindItem selectedItem) {<FILL_FUNCTION_BODY>} @Override public void onResultUpdated(FindResult results) { updateLabel(null); } @Override public String getText() { return myTextField.getText(); } @Override public boolean ignoreCase() { return ignoreCaseCheckBox.isSelected(); } @Override public JComponent getComponent() { return this; } public void requestFocus() { myTextField.requestFocus(); } @Override public void addDocumentChangeListener(DocumentListener listener) { myTextField.getDocument().addDocumentListener(listener); } @Override public void addKeyListener(KeyListener listener) { myTextField.addKeyListener(listener); } @Override public void addIgnoreCaseListener(ItemListener listener) { ignoreCaseCheckBox.addItemListener(listener); } } private class FindResultScrollBarUI extends BasicScrollBarUI { protected void paintTrack(Graphics g, JComponent c, Rectangle trackBounds) { super.paintTrack(g, c, trackBounds); FindResult result = myTerminalPanel.getFindResult(); if (result != null) { int modelHeight = scrollbar.getModel().getMaximum() - scrollbar.getModel().getMinimum(); int anchorHeight = Math.max(2, trackBounds.height / modelHeight); Color color = mySettingsProvider.getTerminalColorPalette() .getColor(mySettingsProvider.getFoundPatternColor() .getBackground()); g.setColor(color); for (FindItem r : result.getItems()) { int where = trackBounds.height * r.getStart().y / modelHeight; g.fillRect(trackBounds.x, trackBounds.y + where, trackBounds.width, anchorHeight); } } } } private static class TerminalLayout implements LayoutManager { public static final String TERMINAL = "TERMINAL"; public static final String SCROLL = "SCROLL"; public static final String FIND = "FIND"; private Component terminal; private Component scroll; private Component find; @Override public void addLayoutComponent(String name, Component comp) { if (TERMINAL.equals(name)) { terminal = comp; } else if (FIND.equals(name)) { find = comp; } else if (SCROLL.equals(name)) { scroll = comp; } else throw new IllegalArgumentException( "unknown component name " + name); } @Override public void removeLayoutComponent(Component comp) { if (comp == terminal) { terminal = null; } if (comp == scroll) { scroll = null; } if (comp == find) { find = comp; } } @Override public Dimension preferredLayoutSize(Container target) { synchronized (target.getTreeLock()) { Dimension dim = new Dimension(0, 0); if (terminal != null) { Dimension d = terminal.getPreferredSize(); dim.width = Math.max(d.width, dim.width); dim.height = Math.max(d.height, dim.height); } if (scroll != null) { Dimension d = scroll.getPreferredSize(); dim.width += d.width; dim.height = Math.max(d.height, dim.height); } if (find != null) { Dimension d = find.getPreferredSize(); dim.width = Math.max(d.width, dim.width); dim.height = Math.max(d.height, dim.height); } Insets insets = target.getInsets(); dim.width += insets.left + insets.right; dim.height += insets.top + insets.bottom; return dim; } } @Override public Dimension minimumLayoutSize(Container target) { synchronized (target.getTreeLock()) { Dimension dim = new Dimension(0, 0); if (terminal != null) { Dimension d = terminal.getMinimumSize(); dim.width = Math.max(d.width, dim.width); dim.height = Math.max(d.height, dim.height); } if (scroll != null) { Dimension d = scroll.getPreferredSize(); dim.width += d.width; dim.height = Math.max(d.height, dim.height); } if (find != null) { Dimension d = find.getMinimumSize(); dim.width = Math.max(d.width, dim.width); dim.height = Math.max(d.height, dim.height); } Insets insets = target.getInsets(); dim.width += insets.left + insets.right; dim.height += insets.top + insets.bottom; return dim; } } @Override public void layoutContainer(Container target) { synchronized (target.getTreeLock()) { Insets insets = target.getInsets(); int top = insets.top; int bottom = target.getHeight() - insets.bottom; int left = insets.left; int right = target.getWidth() - insets.right; Dimension scrollDim = new Dimension(0, 0); if (scroll != null) { scrollDim = scroll.getPreferredSize(); scroll.setBounds(right - scrollDim.width, top, scrollDim.width, bottom - top); } if (terminal != null) { terminal.setBounds(left, top, right - left - scrollDim.width, bottom - top); } if (find != null) { Dimension d = find.getPreferredSize(); find.setBounds(right - d.width - scrollDim.width, top, d.width, d.height); } } } } public void addHyperlinkFilter(HyperlinkFilter filter) { myTextProcessing.addHyperlinkFilter(filter); } @Override public void addListener(TerminalWidgetListener listener) { myListeners.add(listener); } @Override public void removeListener(TerminalWidgetListener listener) { myListeners.remove(listener); } }
FindResult result = myTerminalPanel.getFindResult(); label.setText(((selectedItem != null) ? selectedItem.getIndex() : 0) + " of " + ((result != null) ? result.getItems().size() : 0));
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/PreConnectHandler.java
PreConnectHandler
keyPressed
class PreConnectHandler implements Questioner, KeyListener { private Object mySync = new Object(); private Terminal myTerminal; private StringBuffer myAnswer; private boolean myVisible; public PreConnectHandler(Terminal terminal) { this.myTerminal = terminal; this.myVisible = true; } // These methods will suspend the current thread and wait for // the event handling thread to provide the answer. public String questionHidden(String question) { myVisible = false; String answer = questionVisible(question, null); myVisible = true; return answer; } public String questionVisible(String question, String defValue) { synchronized (mySync) { myTerminal.writeUnwrappedString(question); myAnswer = new StringBuffer(); if (defValue != null) { myAnswer.append(defValue); myTerminal.writeUnwrappedString(defValue); } try { mySync.wait(); } catch (InterruptedException e) { e.printStackTrace(); } String answerStr = myAnswer.toString(); myAnswer = null; return answerStr; } } public void showMessage(String message) { myTerminal.writeUnwrappedString(message); myTerminal.nextLine(); } public void keyPressed(KeyEvent e) {<FILL_FUNCTION_BODY>} public void keyReleased(KeyEvent e) { } public void keyTyped(KeyEvent e) { if (myAnswer == null) return; char c = e.getKeyChar(); if (Character.getType(c) != Character.CONTROL) { if (myVisible) myTerminal.writeCharacters(Character.toString(c)); myAnswer.append(c); } } }
if (myAnswer == null) return; synchronized (mySync) { boolean release = false; switch (e.getKeyCode()) { case KeyEvent.VK_BACK_SPACE: if (myAnswer.length() > 0) { myTerminal.backspace(); myTerminal.eraseInLine(0); myAnswer.deleteCharAt(myAnswer.length() - 1); } break; case KeyEvent.VK_ENTER: myTerminal.nextLine(); release = true; break; } if (release) mySync.notifyAll(); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/TerminalAction.java
TerminalAction
addToMenu
class TerminalAction { private final String myName; private final KeyStroke[] myKeyStrokes; private final Predicate<KeyEvent> myRunnable; private Character myMnemonic = null; private Supplier<Boolean> myEnabledSupplier = null; private Integer myMnemonicKey = null; private boolean mySeparatorBefore = false; private boolean myHidden = false; public TerminalAction(String name, KeyStroke[] keyStrokes, Predicate<KeyEvent> runnable) { myName = name; myKeyStrokes = keyStrokes; myRunnable = runnable; } public boolean matches(KeyEvent e) { for (KeyStroke ks : myKeyStrokes) { if (ks.equals(KeyStroke.getKeyStrokeForEvent(e))) { return true; } } return false; } public boolean perform(KeyEvent e) { if (myEnabledSupplier != null && !myEnabledSupplier.get()) { return false; } return myRunnable.test(e); } public static boolean processEvent(TerminalActionProvider actionProvider, final KeyEvent e) { for (TerminalAction a : actionProvider.getActions()) { if (a.matches(e)) { return a.perform(e); } } if (actionProvider.getNextProvider() != null) { return processEvent(actionProvider.getNextProvider(), e); } return false; } public static boolean addToMenu(JPopupMenu menu, TerminalActionProvider actionProvider) {<FILL_FUNCTION_BODY>} public int getKeyCode() { for (KeyStroke ks : myKeyStrokes) { return ks.getKeyCode(); } return 0; } public int getModifiers() { for (KeyStroke ks : myKeyStrokes) { return ks.getModifiers(); } return 0; } public String getName() { return myName; } public TerminalAction withMnemonic(Character ch) { myMnemonic = ch; return this; } public TerminalAction withMnemonicKey(Integer key) { myMnemonicKey = key; return this; } public boolean isEnabled() { if (myEnabledSupplier != null) { return myEnabledSupplier.get(); } return true; } public TerminalAction withEnabledSupplier(Supplier<Boolean> enabledSupplier) { myEnabledSupplier = enabledSupplier; return this; } public TerminalAction separatorBefore(boolean enabled) { mySeparatorBefore = enabled; return this; } public JMenuItem toMenuItem() { JMenuItem menuItem = new JMenuItem(myName); if (myMnemonic != null) { menuItem.setMnemonic(myMnemonic); } if (myMnemonicKey != null) { menuItem.setMnemonic(myMnemonicKey); } if (myKeyStrokes.length > 0) { menuItem.setAccelerator(myKeyStrokes[0]); } menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { myRunnable.test(null); } }); menuItem.setEnabled(isEnabled()); return menuItem; } public boolean isSeparated() { return mySeparatorBefore; } public boolean isHidden() { return myHidden; } public TerminalAction withHidden(boolean hidden) { myHidden = hidden; return this; } }
boolean added = false; if (actionProvider.getNextProvider() != null) { added = addToMenu(menu, actionProvider.getNextProvider()); } boolean addSeparator = added; for (final TerminalAction a : actionProvider.getActions()) { if (a.isHidden()) { continue; } if (!addSeparator) { addSeparator = a.isSeparated(); } if (addSeparator) { menu.addSeparator(); addSeparator = false; } menu.add(a.toMenuItem()); added = true; } return added;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/TerminalPanel.java
TerminalPanel
changeStateIfNeeded
class TerminalPanel extends JComponent implements TerminalDisplay, TerminalActionProvider { private static final Logger LOG = Logger.getLogger(TerminalPanel.class); private static final long serialVersionUID = -1048763516632093014L; public static final double SCROLL_SPEED = 0.05; /* font related */ private Font myNormalFont; private Font myItalicFont; private Font myBoldFont; private Font myBoldItalicFont; private int myDescent = 0; protected Dimension myCharSize = new Dimension(); private boolean myMonospaced; protected Dimension myTermSize = new Dimension(80, 24); private TerminalStarter myTerminalStarter = null; private MouseMode myMouseMode = MouseMode.MOUSE_REPORTING_NONE; private Point mySelectionStartPoint = null; private TerminalSelection mySelection = null; private final TerminalCopyPasteHandler myCopyPasteHandler; private TerminalPanelListener myTerminalPanelListener; private SettingsProvider mySettingsProvider; final private TerminalTextBuffer myTerminalTextBuffer; final private StyleState myStyleState; /* scroll and cursor */ final private TerminalCursor myCursor = new TerminalCursor(); // we scroll a window [0, terminal_height] in the range // [-history_lines_count, terminal_height] private final BoundedRangeModel myBoundedRangeModel = new DefaultBoundedRangeModel( 0, 80, 0, 80); private boolean myScrollingEnabled = true; protected int myClientScrollOrigin; private final List<KeyListener> myCustomKeyListeners = new CopyOnWriteArrayList<>(); private String myWindowTitle = "Terminal"; private TerminalActionProvider myNextActionProvider; private String myInputMethodUncommittedChars; private Timer myRepaintTimer; private AtomicInteger scrollDy = new AtomicInteger(0); private AtomicBoolean needRepaint = new AtomicBoolean(true); private int myMaxFPS = 50; private int myBlinkingPeriod = 500; private TerminalCoordinates myCoordsAccessor; private String myCurrentPath; // TODO: handle current path if available private SubstringFinder.FindResult myFindResult; private LinkInfo myHoveredHyperlink = null; private int myCursorType = Cursor.DEFAULT_CURSOR; private final TerminalKeyHandler myTerminalKeyHandler = new TerminalKeyHandler(); // public TerminalPanel( SettingsProvider settingsProvider, // TerminalTextBuffer terminalTextBuffer, // StyleState styleState) { public TerminalPanel(SettingsProvider settingsProvider, TerminalTextBuffer terminalTextBuffer, StyleState styleState) { mySettingsProvider = settingsProvider; myTerminalTextBuffer = terminalTextBuffer; myStyleState = styleState; myTermSize.width = terminalTextBuffer.getWidth(); myTermSize.height = terminalTextBuffer.getHeight(); myMaxFPS = mySettingsProvider.maxRefreshRate(); myCopyPasteHandler = createCopyPasteHandler(); updateScrolling(true); enableEvents( AWTEvent.KEY_EVENT_MASK | AWTEvent.INPUT_METHOD_EVENT_MASK); enableInputMethods(true); terminalTextBuffer.addModelListener(new TerminalModelListener() { @Override public void modelChanged() { repaint(); } }); } // protected TerminalCopyPasteHandler createCopyPasteHandler() { return new DefaultTerminalCopyPasteHandler(); } public TerminalPanelListener getTerminalPanelListener() { return myTerminalPanelListener; } @Override public void repaint() { needRepaint.set(true); } private void doRepaint() { super.repaint(); } @Deprecated protected void reinitFontAndResize() { initFont(); sizeTerminalFromComponent(); } protected void initFont() { myNormalFont = createFont(); myBoldFont = myNormalFont.deriveFont(Font.BOLD); myItalicFont = myNormalFont.deriveFont(Font.ITALIC); myBoldItalicFont = myBoldFont.deriveFont(Font.ITALIC); establishFontMetrics(); } public void init() { initFont(); setPreferredSize(new Dimension(getPixelWidth(), getPixelHeight())); setFocusable(true); enableInputMethods(true); setDoubleBuffered(true); setFocusTraversalKeysEnabled(false); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { handleHyperlinks(e.getPoint(), e.isControlDown()); } @Override public void mouseDragged(final MouseEvent e) { if (!isLocalMouseAction(e)) { return; } final Point charCoords = panelToCharCoords(e.getPoint()); if (mySelection == null) { // prevent unlikely case where drag started outside terminal // panel if (mySelectionStartPoint == null) { mySelectionStartPoint = charCoords; } mySelection = new TerminalSelection( new Point(mySelectionStartPoint)); } repaint(); mySelection.updateEnd(charCoords); if (mySettingsProvider.copyOnSelect()) { handleCopyOnSelect(); } if (e.getPoint().y < 0) { moveScrollBar((int) ((e.getPoint().y) * SCROLL_SPEED)); } if (e.getPoint().y > getPixelHeight()) { moveScrollBar((int) ((e.getPoint().y - getPixelHeight()) * SCROLL_SPEED)); } } }); addMouseWheelListener(e -> { if (isLocalMouseAction(e)) { int notches = e.getWheelRotation(); if (Math.abs(e.getPreciseWheelRotation()) < 0.01) { notches = 0; } moveScrollBar(notches); } }); addMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { if (e.getClickCount() == 1) { mySelectionStartPoint = panelToCharCoords(e.getPoint()); mySelection = null; repaint(); } } } @Override public void mouseReleased(final MouseEvent e) { requestFocusInWindow(); repaint(); } @Override public void mouseClicked(final MouseEvent e) { requestFocusInWindow(); Runnable hyperlink = findHyperlink(e.getPoint()); if (hyperlink != null && (myCursorType == Cursor.HAND_CURSOR)) { hyperlink.run(); } else if (e.getButton() == MouseEvent.BUTTON1 && isLocalMouseAction(e)) { int count = e.getClickCount(); if (count == 1) { // do nothing } else if (count == 2) { // select word final Point charCoords = panelToCharCoords( e.getPoint()); Point start = SelectionUtil.getPreviousSeparator( charCoords, myTerminalTextBuffer); Point stop = SelectionUtil.getNextSeparator(charCoords, myTerminalTextBuffer); mySelection = new TerminalSelection(start); mySelection.updateEnd(stop); if (mySettingsProvider.copyOnSelect()) { handleCopyOnSelect(); } } else if (count == 3) { // select line final Point charCoords = panelToCharCoords( e.getPoint()); int startLine = charCoords.y; while (startLine > -getScrollBuffer().getLineCount() && myTerminalTextBuffer.getLine(startLine - 1) .isWrapped()) { startLine--; } int endLine = charCoords.y; while (endLine < myTerminalTextBuffer.getHeight() && myTerminalTextBuffer.getLine(endLine) .isWrapped()) { endLine++; } mySelection = new TerminalSelection( new Point(0, startLine)); mySelection.updateEnd( new Point(myTermSize.width, endLine)); if (mySettingsProvider.copyOnSelect()) { handleCopyOnSelect(); } } } else if (e.getButton() == MouseEvent.BUTTON2 && mySettingsProvider.pasteOnMiddleMouseClick() && isLocalMouseAction(e)) { handlePasteSelection(); } else if (e.getButton() == MouseEvent.BUTTON3) { if (mySettingsProvider.pasteOnMiddleMouseClick() && isLocalMouseAction(e)) { handlePasteSelection(); } else { JPopupMenu popup = createPopupMenu(); popup.show(e.getComponent(), e.getX(), e.getY()); } } repaint(); } }); addComponentListener(new ComponentAdapter() { @Override public void componentResized(final ComponentEvent e) { sizeTerminalFromComponent(); } }); addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { myCursor.cursorChanged(); } @Override public void focusLost(FocusEvent e) { myCursor.cursorChanged(); handleHyperlinks(e.getComponent(), false); } }); myBoundedRangeModel.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { myClientScrollOrigin = myBoundedRangeModel.getValue(); repaint(); } }); createRepaintTimer(); } private void handleHyperlinks(Point p, boolean isControlDown) { HyperlinkStyle hyperlinkStyle = findHyperlink(p); if (hyperlinkStyle != null) { if (hyperlinkStyle .getHighlightMode() == HyperlinkStyle.HighlightMode.ALWAYS || (hyperlinkStyle .getHighlightMode() == HyperlinkStyle.HighlightMode.HOVER && isControlDown)) { updateCursor(Cursor.HAND_CURSOR); myHoveredHyperlink = hyperlinkStyle.getLinkInfo(); return; } } myHoveredHyperlink = null; if (myCursorType != Cursor.DEFAULT_CURSOR) { updateCursor(Cursor.DEFAULT_CURSOR); repaint(); } } private void handleHyperlinks(Component component, boolean controlDown) { PointerInfo a = MouseInfo.getPointerInfo(); if (a != null) { Point b = a.getLocation(); SwingUtilities.convertPointFromScreen(b, component); handleHyperlinks(b, controlDown); } } // private HyperlinkStyle findHyperlink(Point p) { p = panelToCharCoords(p); if (p.x >= 0 && p.x < myTerminalTextBuffer.getWidth() && p.y >= -myTerminalTextBuffer.getHistoryLinesCount() && p.y <= myTerminalTextBuffer.getHeight()) { TextStyle style = myTerminalTextBuffer.getStyleAt(p.x, p.y); if (style instanceof HyperlinkStyle) { return (HyperlinkStyle) style; } } return null; } private void updateCursor(int cursorType) { if (cursorType != myCursorType) { myCursorType = cursorType; // noinspection MagicConstant setCursor(new Cursor(myCursorType)); } } private void createRepaintTimer() { if (myRepaintTimer != null) { myRepaintTimer.stop(); } myRepaintTimer = new Timer(1000 / myMaxFPS, new WeakRedrawTimer(this)); myRepaintTimer.start(); } public boolean isLocalMouseAction(MouseEvent e) { return mySettingsProvider.forceActionOnMouseReporting() || (isMouseReporting() == e.isShiftDown()); } public boolean isRemoteMouseAction(MouseEvent e) { return isMouseReporting() && !e.isShiftDown(); } protected boolean isRetina() { return UIUtil.isRetina(); } public void setBlinkingPeriod(int blinkingPeriod) { myBlinkingPeriod = blinkingPeriod; } public void setCoordAccessor(TerminalCoordinates coordAccessor) { myCoordsAccessor = coordAccessor; } public void setFindResult(SubstringFinder.FindResult findResult) { myFindResult = findResult; repaint(); } public SubstringFinder.FindResult getFindResult() { return myFindResult; } public FindItem selectPrevFindResultItem() { return selectPrevOrNextFindResultItem(false); } public FindItem selectNextFindResultItem() { return selectPrevOrNextFindResultItem(true); } protected FindItem selectPrevOrNextFindResultItem(boolean next) { if (myFindResult != null) { SubstringFinder.FindResult.FindItem item = next ? myFindResult.nextFindItem() : myFindResult.prevFindItem(); if (item != null) { mySelection = new TerminalSelection( new Point(item.getStart().x, item.getStart().y - myTerminalTextBuffer .getHistoryLinesCount()), new Point(item.getEnd().x, item.getEnd().y - myTerminalTextBuffer.getHistoryLinesCount())); if (mySelection.getStart().y < getTerminalTextBuffer() .getHeight() / 2) { myBoundedRangeModel.setValue(mySelection.getStart().y - getTerminalTextBuffer().getHeight() / 2); } else { myBoundedRangeModel.setValue(0); } repaint(); return item; } } return null; } static class WeakRedrawTimer implements ActionListener { private WeakReference<TerminalPanel> ref; public WeakRedrawTimer(TerminalPanel terminalPanel) { this.ref = new WeakReference<TerminalPanel>(terminalPanel); } @Override public void actionPerformed(ActionEvent e) { TerminalPanel terminalPanel = ref.get(); if (terminalPanel != null) { terminalPanel.myCursor.changeStateIfNeeded(); terminalPanel.updateScrolling(false); if (terminalPanel.needRepaint.getAndSet(false)) { try { terminalPanel.doRepaint(); } catch (Exception ex) { LOG.error("Error while terminal panel redraw", ex); } } } else { // terminalPanel was garbage collected Timer timer = (Timer) e.getSource(); timer.removeActionListener(this); timer.stop(); } } } @Override public void terminalMouseModeSet(MouseMode mode) { myMouseMode = mode; } private boolean isMouseReporting() { return myMouseMode != MouseMode.MOUSE_REPORTING_NONE; } private void scrollToBottom() { myBoundedRangeModel.setValue(myTermSize.height); } private void pageUp() { moveScrollBar(-myTermSize.height); } private void pageDown() { moveScrollBar(myTermSize.height); } private void scrollUp() { moveScrollBar(-1); } private void scrollDown() { moveScrollBar(1); } private void moveScrollBar(int k) { myBoundedRangeModel.setValue(myBoundedRangeModel.getValue() + k); } protected Font createFont() { return mySettingsProvider.getTerminalFont(); } protected Point panelToCharCoords(final Point p) { int x = Math.min((p.x - getInsetX()) / myCharSize.width, getColumnCount() - 1); x = Math.max(0, x); int y = Math.min(p.y / myCharSize.height, getRowCount() - 1) + myClientScrollOrigin; return new Point(x, y); } protected Point charToPanelCoords(final Point p) { return new Point(p.x * myCharSize.width + getInsetX(), (p.y - myClientScrollOrigin) * myCharSize.height); } // private void copySelection( Point selectionStart, // Point selectionEnd, // boolean useSystemSelectionClipboardIfAvailable) { private void copySelection(Point selectionStart, Point selectionEnd, boolean useSystemSelectionClipboardIfAvailable) { if (selectionStart == null || selectionEnd == null) { return; } String selectionText = SelectionUtil.getSelectionText(selectionStart, selectionEnd, myTerminalTextBuffer); if (selectionText.length() != 0) { myCopyPasteHandler.setContents(selectionText, useSystemSelectionClipboardIfAvailable); } } private void pasteFromClipboard( boolean useSystemSelectionClipboardIfAvailable) { String text = myCopyPasteHandler .getContents(useSystemSelectionClipboardIfAvailable); if (text == null) { return; } try { // Sanitize clipboard text to use CR as the line separator. // See https://github.com/JetBrains/jediterm/issues/136. if (!UIUtil.isWindows) { // On Windows, Java automatically does this CRLF->LF // sanitization, but // other terminals on Unix typically also do this sanitization, // so // maybe JediTerm also should. text = text.replace("\r\n", "\n"); } text = text.replace('\n', '\r'); myTerminalStarter.sendString(text); } catch (RuntimeException e) { LOG.info(e); } } // private String getClipboardString() { return myCopyPasteHandler.getContents(false); } protected void drawImage(Graphics2D gfx, BufferedImage image, int x, int y, ImageObserver observer) { gfx.drawImage(image, x, y, image.getWidth(), image.getHeight(), observer); } protected BufferedImage createBufferedImage(int width, int height) { return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); } // public Dimension getTerminalSizeFromComponent() { int newWidth = (getWidth() - getInsetX()) / myCharSize.width; int newHeight = getHeight() / myCharSize.height; return newHeight > 0 && newWidth > 0 ? new Dimension(newWidth, newHeight) : null; } private void sizeTerminalFromComponent() { if (myTerminalStarter != null) { Dimension newSize = getTerminalSizeFromComponent(); if (newSize != null) { myTerminalStarter.postResize(newSize, RequestOrigin.User); } } } public void setTerminalStarter(final TerminalStarter terminalStarter) { myTerminalStarter = terminalStarter; sizeTerminalFromComponent(); } // public void addCustomKeyListener( KeyListener keyListener) { public void addCustomKeyListener(KeyListener keyListener) { myCustomKeyListeners.add(keyListener); } // public void removeCustomKeyListener( KeyListener keyListener) { public void removeCustomKeyListener(KeyListener keyListener) { myCustomKeyListeners.remove(keyListener); } @Deprecated public Dimension requestResize(final Dimension newSize, final RequestOrigin origin, int cursorY, JediTerminal.ResizeHandler resizeHandler) { return requestResize(newSize, origin, 0, cursorY, resizeHandler); } public Dimension requestResize(final Dimension newSize, final RequestOrigin origin, int cursorX, int cursorY, JediTerminal.ResizeHandler resizeHandler) { if (!newSize.equals(myTermSize)) { myTerminalTextBuffer.lock(); try { myTerminalTextBuffer.resize(newSize, origin, cursorX, cursorY, resizeHandler, mySelection); } finally { myTerminalTextBuffer.unlock(); } myTermSize = (Dimension) newSize.clone(); final Dimension pixelDimension = new Dimension(getPixelWidth(), getPixelHeight()); setPreferredSize(pixelDimension); if (myTerminalPanelListener != null) { myTerminalPanelListener.onPanelResize(pixelDimension, origin); } SwingUtilities.invokeLater(() -> updateScrolling(true)); } return new Dimension(getPixelWidth(), getPixelHeight()); } public void setTerminalPanelListener( final TerminalPanelListener terminalPanelListener) { myTerminalPanelListener = terminalPanelListener; } private void establishFontMetrics() { final BufferedImage img = createBufferedImage(1, 1); final Graphics2D graphics = img.createGraphics(); graphics.setFont(myNormalFont); final float lineSpace = mySettingsProvider.getLineSpace(); final FontMetrics fo = graphics.getFontMetrics(); myDescent = fo.getDescent(); myCharSize.width = fo.charWidth('W'); // The magic +2 here is to give lines a tiny bit of extra height to // avoid clipping when rendering some Apple // emoji, which are slightly higher than the font metrics reported // character height :( myCharSize.height = fo.getHeight() + (int) (lineSpace * 2) + 2; myDescent += lineSpace; myMonospaced = isMonospaced(fo); if (!myMonospaced) { LOG.info("WARNING: Font " + myNormalFont.getName() + " is non-monospaced"); } img.flush(); graphics.dispose(); } private static boolean isMonospaced(FontMetrics fontMetrics) { boolean isMonospaced = true; int charWidth = -1; for (int codePoint = 0; codePoint < 128; codePoint++) { if (Character.isValidCodePoint(codePoint)) { char character = (char) codePoint; if (isWordCharacter(character)) { int w = fontMetrics.charWidth(character); if (charWidth != -1) { if (w != charWidth) { isMonospaced = false; break; } } else { charWidth = w; } } } } return isMonospaced; } private static boolean isWordCharacter(char character) { return Character.isLetterOrDigit(character); } protected void setupAntialiasing(Graphics graphics) { if (graphics instanceof Graphics2D) { Graphics2D myGfx = (Graphics2D) graphics; final Object mode = mySettingsProvider.useAntialiasing() ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF; final RenderingHints hints = new RenderingHints( RenderingHints.KEY_TEXT_ANTIALIASING, mode); myGfx.setRenderingHints(hints); } } @Override public Color getBackground() { return getPalette().getColor(myStyleState.getBackground()); } @Override public Color getForeground() { return getPalette().getColor(myStyleState.getForeground()); } @Override public void paintComponent(final Graphics g) { final Graphics2D gfx = (Graphics2D) g; setupAntialiasing(gfx); gfx.setColor(getBackground()); gfx.fillRect(0, 0, getWidth(), getHeight()); try { myTerminalTextBuffer.lock(); // update myClientScrollOrigin as scrollArea might have been invoked // after last WeakRedrawTimer action updateScrolling(false); myTerminalTextBuffer.processHistoryAndScreenLines( myClientScrollOrigin, myTermSize.height, new StyledTextConsumer() { final int columnCount = getColumnCount(); // @Override // public void consume(int x, int y, // TextStyle style, // CharBuffer characters, int startRow) { @Override public void consume(int x, int y, TextStyle style, CharBuffer characters, int startRow) { int row = y - startRow; drawCharacters(x, row, style, characters, gfx); if (myFindResult != null) { List<Pair<Integer, Integer>> ranges = myFindResult .getRanges(characters); if (ranges != null) { for (Pair<Integer, Integer> range : ranges) { TextStyle foundPatternStyle = getFoundPattern( style); CharBuffer foundPatternChars = characters .subBuffer(range); drawCharacters(x + range.first, row, foundPatternStyle, foundPatternChars, gfx); } } } if (mySelection != null) { Pair<Integer, Integer> interval = mySelection .intersect(x, row + myClientScrollOrigin, characters.length()); if (interval != null) { TextStyle selectionStyle = getSelectionStyle( style); CharBuffer selectionChars = characters .subBuffer(interval.first - x, interval.second); drawCharacters(interval.first, row, selectionStyle, selectionChars, gfx); } } } @Override public void consumeNul(int x, int y, int nulIndex, TextStyle style, CharBuffer characters, int startRow) { int row = y - startRow; if (mySelection != null) { // compute intersection with all NUL areas, // non-breaking Pair<Integer, Integer> interval = mySelection .intersect(nulIndex, row + myClientScrollOrigin, columnCount - nulIndex); if (interval != null) { TextStyle selectionStyle = getSelectionStyle( style); drawCharacters(x, row, selectionStyle, characters, gfx); return; } } drawCharacters(x, row, style, characters, gfx); } @Override public void consumeQueue(int x, int y, int nulIndex, int startRow) { if (x < columnCount) { consumeNul(x, y, nulIndex, TextStyle.EMPTY, new CharBuffer(CharUtils.EMPTY_CHAR, columnCount - x), startRow); } } }); int cursorY = myCursor.getCoordY(); if ((myClientScrollOrigin + getRowCount() > cursorY) && !hasUncommittedChars()) { int cursorX = myCursor.getCoordX(); Pair<Character, TextStyle> sc = myTerminalTextBuffer .getStyledCharAt(cursorX, cursorY); String cursorChar = "" + sc.first; if (Character.isHighSurrogate(sc.first)) { cursorChar += myTerminalTextBuffer .getStyledCharAt(cursorX + 1, cursorY).first; } TextStyle normalStyle = sc.second != null ? sc.second : myStyleState.getCurrent(); TextStyle selectionStyle = getSelectionStyle(normalStyle); boolean inSelection = inSelection(cursorX, cursorY); myCursor.drawCursor(cursorChar, gfx, inSelection ? selectionStyle : normalStyle); } } finally { myTerminalTextBuffer.unlock(); } drawInputMethodUncommitedChars(gfx); drawMargins(gfx, getWidth(), getHeight()); } // // private TextStyle getSelectionStyle( TextStyle style) { private TextStyle getSelectionStyle(TextStyle style) { if (mySettingsProvider.useInverseSelectionColor()) { return getInversedStyle(style); } TextStyle.Builder builder = style.toBuilder(); TextStyle mySelectionStyle = mySettingsProvider.getSelectionColor(); builder.setBackground(mySelectionStyle.getBackground()); builder.setForeground(mySelectionStyle.getForeground()); if (builder instanceof HyperlinkStyle.Builder) { return ((HyperlinkStyle.Builder) builder).build(true); } return builder.build(); } // private TextStyle getFoundPattern(// TextStyle style) { TextStyle.Builder builder = style.toBuilder(); TextStyle foundPattern = mySettingsProvider.getFoundPatternColor(); builder.setBackground(foundPattern.getBackground()); builder.setForeground(foundPattern.getForeground()); return builder.build(); } private void drawInputMethodUncommitedChars(Graphics2D gfx) { if (hasUncommittedChars()) { int xCoord = (myCursor.getCoordX() + 1) * myCharSize.width + getInsetX(); int y = myCursor.getCoordY() + 1; int yCoord = y * myCharSize.height - 3; int len = (myInputMethodUncommittedChars.length()) * myCharSize.width; gfx.setColor(getBackground()); gfx.fillRect(xCoord, (y - 1) * myCharSize.height - 3, len, myCharSize.height); gfx.setColor(getForeground()); gfx.setFont(myNormalFont); gfx.drawString(myInputMethodUncommittedChars, xCoord, yCoord); Stroke saved = gfx.getStroke(); BasicStroke dotted = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[] { 0, 2, 0, 2 }, 0); gfx.setStroke(dotted); gfx.drawLine(xCoord, yCoord, xCoord + len, yCoord); gfx.setStroke(saved); } } private boolean hasUncommittedChars() { return myInputMethodUncommittedChars != null && myInputMethodUncommittedChars.length() > 0; } private boolean inSelection(int x, int y) { return mySelection != null && mySelection.contains(new Point(x, y)); } @Override public void processKeyEvent(final KeyEvent e) { handleKeyEvent(e); handleHyperlinks(e.getComponent(), e.isControlDown()); e.consume(); } // also called from com.intellij.terminal.JBTerminalPanel public void handleKeyEvent(// KeyEvent e) { final int id = e.getID(); if (id == KeyEvent.KEY_PRESSED) { for (KeyListener keyListener : myCustomKeyListeners) { keyListener.keyPressed(e); } } else if (id == KeyEvent.KEY_TYPED) { for (KeyListener keyListener : myCustomKeyListeners) { keyListener.keyTyped(e); } } } public int getPixelWidth() { return myCharSize.width * myTermSize.width + getInsetX(); } public int getPixelHeight() { return myCharSize.height * myTermSize.height; } public int getColumnCount() { return myTermSize.width; } public int getRowCount() { return myTermSize.height; } public String getWindowTitle() { return myWindowTitle; } protected int getInsetX() { return 4; } public void addTerminalMouseListener(final TerminalMouseListener listener) { addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mousePressed(p.x, p.y, e); } } @Override public void mouseReleased(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mouseReleased(p.x, p.y, e); } } }); addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { mySelection = null; Point p = panelToCharCoords(e.getPoint()); listener.mouseWheelMoved(p.x, p.y, e); } } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mouseMoved(p.x, p.y, e); } } @Override public void mouseDragged(MouseEvent e) { if (mySettingsProvider.enableMouseReporting() && isRemoteMouseAction(e)) { Point p = panelToCharCoords(e.getPoint()); listener.mouseDragged(p.x, p.y, e); } } }); } // KeyListener getTerminalKeyListener() { return myTerminalKeyHandler; } public enum TerminalCursorState { SHOWING, HIDDEN, NO_FOCUS; } public class TerminalCursor { // cursor state private boolean myCursorIsShown; // blinking state protected Point myCursorCoordinates = new Point(); private CursorShape myShape = CursorShape.BLINK_BLOCK; // terminal modes private boolean myShouldDrawCursor = true; private boolean myBlinking = true; private long myLastCursorChange; private boolean myCursorHasChanged; public void setX(int x) { myCursorCoordinates.x = x; cursorChanged(); } public void setY(int y) { myCursorCoordinates.y = y; cursorChanged(); } public int getCoordX() { return myCursorCoordinates.x; } public int getCoordY() { return myCursorCoordinates.y - 1 - myClientScrollOrigin; } public void setShouldDrawCursor(boolean shouldDrawCursor) { myShouldDrawCursor = shouldDrawCursor; } public void setBlinking(boolean blinking) { myBlinking = blinking; } public boolean isBlinking() { return myBlinking && (getBlinkingPeriod() > 0); } public void cursorChanged() { myCursorHasChanged = true; myLastCursorChange = System.currentTimeMillis(); repaint(); } private boolean cursorShouldChangeBlinkState(long currentTime) { return currentTime - myLastCursorChange > getBlinkingPeriod(); } public void changeStateIfNeeded() {<FILL_FUNCTION_BODY>} private TerminalCursorState computeBlinkingState() { if (!isBlinking() || myCursorHasChanged || myCursorIsShown) { return TerminalCursorState.SHOWING; } return TerminalCursorState.HIDDEN; } private TerminalCursorState computeCursorState() { if (!myShouldDrawCursor) { return TerminalCursorState.HIDDEN; } if (!isFocusOwner()) { return TerminalCursorState.NO_FOCUS; } return computeBlinkingState(); } void drawCursor(String c, Graphics2D gfx, TextStyle style) { TerminalCursorState state = computeCursorState(); // hidden: do nothing if (state == TerminalCursorState.HIDDEN) { return; } final int x = getCoordX(); final int y = getCoordY(); // Outside bounds of window: do nothing if (y < 0 || y >= myTermSize.height) { return; } CharBuffer buf = new CharBuffer(c); int xCoord = x * myCharSize.width + getInsetX(); int yCoord = y * myCharSize.height; int textLength = CharUtils.getTextLengthDoubleWidthAware( buf.getBuf(), buf.getStart(), buf.length(), mySettingsProvider.ambiguousCharsAreDoubleWidth()); int height = Math.min(myCharSize.height, getHeight() - yCoord); int width = Math.min( textLength * TerminalPanel.this.myCharSize.width, TerminalPanel.this.getWidth() - xCoord); int lineStrokeSize = 2; Color fgColor = getPalette().getColor( myStyleState.getForeground(style.getForegroundForRun())); TextStyle inversedStyle = getInversedStyle(style); Color inverseBg = getPalette().getColor(myStyleState .getBackground(inversedStyle.getBackgroundForRun())); switch (myShape) { case BLINK_BLOCK: case STEADY_BLOCK: if (state == TerminalCursorState.SHOWING) { gfx.setColor(inverseBg); gfx.fillRect(xCoord, yCoord, width, height); drawCharacters(x, y, inversedStyle, buf, gfx); } else { gfx.setColor(fgColor); gfx.drawRect(xCoord, yCoord, width, height); } break; case BLINK_UNDERLINE: case STEADY_UNDERLINE: gfx.setColor(fgColor); gfx.fillRect(xCoord, yCoord + height, width, lineStrokeSize); break; case BLINK_VERTICAL_BAR: case STEADY_VERTICAL_BAR: gfx.setColor(fgColor); gfx.fillRect(xCoord, yCoord, lineStrokeSize, height); break; } } void setShape(CursorShape shape) { this.myShape = shape; } } private int getBlinkingPeriod() { if (myBlinkingPeriod != mySettingsProvider.caretBlinkingMs()) { setBlinkingPeriod(mySettingsProvider.caretBlinkingMs()); } return myBlinkingPeriod; } protected void drawImage(Graphics2D g, BufferedImage image, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) { g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null); } // private TextStyle getInversedStyle(// TextStyle style) { TextStyle.Builder builder = new TextStyle.Builder(style); builder.setOption(Option.INVERSE, !style.hasOption(Option.INVERSE)); if (style.getForeground() == null) { builder.setForeground(myStyleState.getForeground()); } if (style.getBackground() == null) { builder.setBackground(myStyleState.getBackground()); } return builder.build(); } private void drawCharacters(int x, int y, TextStyle style, CharBuffer buf, Graphics2D gfx) { int xCoord = x * myCharSize.width + getInsetX(); int yCoord = y * myCharSize.height; if (xCoord < 0 || xCoord > getWidth() || yCoord < 0 || yCoord > getHeight()) { return; } int textLength = CharUtils.getTextLengthDoubleWidthAware(buf.getBuf(), buf.getStart(), buf.length(), mySettingsProvider.ambiguousCharsAreDoubleWidth()); int height = Math.min(myCharSize.height, getHeight() - yCoord); int width = Math.min(textLength * TerminalPanel.this.myCharSize.width, TerminalPanel.this.getWidth() - xCoord); if (style instanceof HyperlinkStyle) { HyperlinkStyle hyperlinkStyle = (HyperlinkStyle) style; if (hyperlinkStyle .getHighlightMode() == HyperlinkStyle.HighlightMode.ALWAYS || (isHoveredHyperlink(hyperlinkStyle) && hyperlinkStyle .getHighlightMode() == HyperlinkStyle.HighlightMode.HOVER)) { // substitute text style with the hyperlink highlight style if // applicable style = hyperlinkStyle.getHighlightStyle(); } } Color backgroundColor = getPalette().getColor( myStyleState.getBackground(style.getBackgroundForRun())); gfx.setColor(backgroundColor); gfx.fillRect(xCoord, yCoord, width, height); if (buf.isNul()) { return; // nothing more to do } drawChars(x, y, buf, style, gfx); gfx.setColor(getPalette().getColor( myStyleState.getForeground(style.getForegroundForRun()))); int baseLine = (y + 1) * myCharSize.height - myDescent; if (style.hasOption(TextStyle.Option.UNDERLINED)) { gfx.drawLine(xCoord, baseLine + 3, (x + textLength) * myCharSize.width + getInsetX(), baseLine + 3); } } private boolean isHoveredHyperlink(// HyperlinkStyle link) { return myHoveredHyperlink == link.getLinkInfo(); } /** * Draw every char in separate terminal cell to guaranty equal width for * different lines. Nevertheless to improve kerning we draw word characters * as one block for monospaced fonts. */ private void drawChars(int x, int y, CharBuffer buf, TextStyle style, Graphics2D gfx) { int blockLen = 1; int offset = 0; int drawCharsOffset = 0; // workaround to fix Swing bad rendering of bold special chars on Linux // TODO required for italic? CharBuffer renderingBuffer; if (mySettingsProvider.DECCompatibilityMode() && style.hasOption(TextStyle.Option.BOLD)) { renderingBuffer = CharUtils.heavyDecCompatibleBuffer(buf); } else { renderingBuffer = buf; } while (offset + blockLen <= buf.length()) { if (renderingBuffer.getBuf()[buf.getStart() + offset] == CharUtils.DWC) { offset += blockLen; drawCharsOffset += blockLen; continue; // dont' draw second part(fake one) of double width // character } Font font = getFontToDisplay(buf.charAt(offset + blockLen - 1), style); // while (myMonospaced && (offset + blockLen < buf.getLength()) && isWordCharacter(buf.charAt(offset + blockLen - 1)) // && (font == getFontToDisplay(buf.charAt(offset + blockLen - 1), style))) { // blockLen++; // } if (offset + 2 <= buf.length() && Character.isSurrogatePair( renderingBuffer.getBuf()[buf.getStart() + offset], renderingBuffer.getBuf()[buf.getStart() + offset + 1])) { blockLen = 2; } gfx.setFont(font); int descent = gfx.getFontMetrics(font).getDescent(); int baseLine = (y + 1) * myCharSize.height - descent; int xCoord = (x + drawCharsOffset) * myCharSize.width + getInsetX(); int textLength = CharUtils.getTextLengthDoubleWidthAware( buf.getBuf(), buf.getStart() + offset, blockLen, mySettingsProvider.ambiguousCharsAreDoubleWidth()); int yCoord = y * myCharSize.height; gfx.setClip(xCoord, yCoord, getWidth() - xCoord, getHeight() - yCoord); gfx.setColor(getPalette().getColor( myStyleState.getForeground(style.getForegroundForRun()))); gfx.drawChars(renderingBuffer.getBuf(), buf.getStart() + offset, blockLen, xCoord, baseLine); drawCharsOffset += blockLen; offset += blockLen; blockLen = 1; } gfx.setClip(null); } protected Font getFontToDisplay(char c, TextStyle style) { boolean bold = style.hasOption(TextStyle.Option.BOLD); boolean italic = style.hasOption(TextStyle.Option.ITALIC); // workaround to fix Swing bad rendering of bold special chars on Linux if (bold && mySettingsProvider.DECCompatibilityMode() && CharacterSets.isDecBoxChar(c)) { return myNormalFont; } return bold ? (italic ? myBoldItalicFont : myBoldFont) : (italic ? myItalicFont : myNormalFont); } private ColorPalette getPalette() { return mySettingsProvider.getTerminalColorPalette(); } private void drawMargins(Graphics2D gfx, int width, int height) { gfx.setColor(getBackground()); gfx.fillRect(0, height, getWidth(), getHeight() - height); gfx.fillRect(width, 0, getWidth() - width, getHeight()); } // Called in a background thread with myTerminalTextBuffer.lock() acquired public void scrollArea(final int scrollRegionTop, final int scrollRegionSize, int dy) { scrollDy.addAndGet(dy); mySelection = null; } private void updateScrolling(boolean forceUpdate) { int dy = scrollDy.getAndSet(0); if (dy == 0 && !forceUpdate) { return; } if (myScrollingEnabled) { int value = myBoundedRangeModel.getValue(); int historyLineCount = myTerminalTextBuffer.getHistoryLinesCount(); if (value == 0) { myBoundedRangeModel.setRangeProperties(0, myTermSize.height, -historyLineCount, myTermSize.height, false); } else { // if scrolled to a specific area, update scroll to keep showing // this area myBoundedRangeModel.setRangeProperties( Math.min(Math.max(value + dy, -historyLineCount), myTermSize.height), myTermSize.height, -historyLineCount, myTermSize.height, false); } } else { myBoundedRangeModel.setRangeProperties(0, myTermSize.height, 0, myTermSize.height, false); } } public void setCursor(final int x, final int y) { myCursor.setX(x); myCursor.setY(y); } @Override public void setCursorShape(CursorShape shape) { myCursor.setShape(shape); switch (shape) { case STEADY_BLOCK: case STEADY_UNDERLINE: case STEADY_VERTICAL_BAR: myCursor.myBlinking = false; break; case BLINK_BLOCK: case BLINK_UNDERLINE: case BLINK_VERTICAL_BAR: myCursor.myBlinking = true; break; } } public void beep() { if (mySettingsProvider.audibleBell()) { Toolkit.getDefaultToolkit().beep(); } } public BoundedRangeModel getBoundedRangeModel() { return myBoundedRangeModel; } public TerminalTextBuffer getTerminalTextBuffer() { return myTerminalTextBuffer; } public TerminalSelection getSelection() { return mySelection; } @Override public boolean ambiguousCharsAreDoubleWidth() { return mySettingsProvider.ambiguousCharsAreDoubleWidth(); } public LinesBuffer getScrollBuffer() { return myTerminalTextBuffer.getHistoryBuffer(); } @Override public void setCursorVisible(boolean shouldDrawCursor) { myCursor.setShouldDrawCursor(shouldDrawCursor); } protected JPopupMenu createPopupMenu() { JPopupMenu popup = new JPopupMenu(); TerminalAction.addToMenu(popup, this); return popup; } public void setScrollingEnabled(boolean scrollingEnabled) { myScrollingEnabled = scrollingEnabled; SwingUtilities.invokeLater(() -> updateScrolling(true)); } @Override public void setBlinkingCursor(boolean enabled) { myCursor.setBlinking(enabled); } public TerminalCursor getTerminalCursor() { return myCursor; } public TerminalOutputStream getTerminalOutputStream() { return myTerminalStarter; } @Override public void setWindowTitle(String name) { System.out.println("########## name: " + name); myWindowTitle = name; if (myTerminalPanelListener != null) { myTerminalPanelListener.onTitleChanged(myWindowTitle); } } @Override public void setCurrentPath(String path) { System.out.println("########## path: " + path); myCurrentPath = path; } @Override public List<TerminalAction> getActions() { // return Lists.newArrayList( // new TerminalAction("Open as URL", new KeyStroke[0], // input -> openSelectionAsURL()) // .withEnabledSupplier(this::selectionTextIsUrl), // new TerminalAction("Copy", // mySettingsProvider.getCopyKeyStrokes(), // input -> handleCopy()).withMnemonicKey(KeyEvent.VK_C) // .withEnabledSupplier(() -> mySelection != null), // new TerminalAction("Paste", // mySettingsProvider.getPasteKeyStrokes(), input -> { // handlePaste(); // return true; // }).withMnemonicKey(KeyEvent.VK_P).withEnabledSupplier( // () -> getClipboardString() != null), // new TerminalAction("Clear Buffer", // mySettingsProvider.getClearBufferKeyStrokes(), // input -> { // clearBuffer(); // return true; // }).withMnemonicKey(KeyEvent.VK_K) // .withEnabledSupplier(() -> !myTerminalTextBuffer // .isUsingAlternateBuffer()) // .separatorBefore(true), // new TerminalAction("Page Up", // mySettingsProvider.getPageUpKeyStrokes(), input -> { // pageUp(); // return true; // }).withEnabledSupplier(() -> !myTerminalTextBuffer // .isUsingAlternateBuffer()) // .separatorBefore(true), // new TerminalAction("Page Down", // mySettingsProvider.getPageDownKeyStrokes(), input -> { // pageDown(); // return true; // }).withEnabledSupplier(() -> !myTerminalTextBuffer // .isUsingAlternateBuffer()), // new TerminalAction("Line Up", // mySettingsProvider.getLineUpKeyStrokes(), input -> { // scrollUp(); // return true; // }).withEnabledSupplier(() -> !myTerminalTextBuffer // .isUsingAlternateBuffer()) // .separatorBefore(true), // new TerminalAction("Line Down", // mySettingsProvider.getLineDownKeyStrokes(), input -> { // scrollDown(); // return true; // })); ArrayList<TerminalAction> list = new ArrayList<>(); list.addAll(Arrays.asList( new TerminalAction("Open as URL", new KeyStroke[0], input -> openSelectionAsURL()) .withEnabledSupplier(this::selectionTextIsUrl), new TerminalAction("Copy", mySettingsProvider.getCopyKeyStrokes(), input -> handleCopy()).withMnemonicKey(KeyEvent.VK_C) .withEnabledSupplier(() -> mySelection != null), new TerminalAction("Paste", mySettingsProvider.getPasteKeyStrokes(), input -> { handlePaste(); return true; }).withMnemonicKey(KeyEvent.VK_P).withEnabledSupplier( () -> getClipboardString() != null), new TerminalAction("Clear Buffer", mySettingsProvider.getClearBufferKeyStrokes(), input -> { clearBuffer(); return true; }).withMnemonicKey(KeyEvent.VK_K) .withEnabledSupplier(() -> !myTerminalTextBuffer .isUsingAlternateBuffer()) .separatorBefore(true), new TerminalAction("Page Up", mySettingsProvider.getPageUpKeyStrokes(), input -> { pageUp(); return true; }).withEnabledSupplier(() -> !myTerminalTextBuffer .isUsingAlternateBuffer()) .separatorBefore(true), new TerminalAction("Page Down", mySettingsProvider.getPageDownKeyStrokes(), input -> { pageDown(); return true; }).withEnabledSupplier(() -> !myTerminalTextBuffer .isUsingAlternateBuffer()), new TerminalAction("Line Up", mySettingsProvider.getLineUpKeyStrokes(), input -> { scrollUp(); return true; }).withEnabledSupplier(() -> !myTerminalTextBuffer .isUsingAlternateBuffer()) .separatorBefore(true), new TerminalAction("Line Down", mySettingsProvider.getLineDownKeyStrokes(), input -> { scrollDown(); return true; }))); return list; } // private Boolean selectionTextIsUrl() { String selectionText = getSelectionText(); if (selectionText != null) { try { URI uri = new URI(selectionText); // noinspection ResultOfMethodCallIgnored uri.toURL(); return true; } catch (Exception e) { // pass } } return false; } // private String getSelectionText() { if (mySelection != null) { Pair<Point, Point> points = mySelection .pointsForRun(myTermSize.width); if (points.first != null || points.second != null) { return SelectionUtil.getSelectionText(points.first, points.second, myTerminalTextBuffer); } } return null; } protected boolean openSelectionAsURL() { if (Desktop.isDesktopSupported()) { try { String selectionText = getSelectionText(); if (selectionText != null) { Desktop.getDesktop().browse(new URI(selectionText)); } } catch (Exception e) { // ok then } } return false; } public void clearBuffer() { clearBuffer(true); } /** * @param keepLastLine true to keep last line (e.g. to keep terminal prompt) * false to clear entire terminal panel (relevant for * terminal console) */ protected void clearBuffer(boolean keepLastLine) { if (!myTerminalTextBuffer.isUsingAlternateBuffer()) { myTerminalTextBuffer.clearHistory(); if (myCoordsAccessor != null) { if (keepLastLine) { if (myCoordsAccessor.getY() > 0) { TerminalLine lastLine = myTerminalTextBuffer .getLine(myCoordsAccessor.getY() - 1); myTerminalTextBuffer.clearAll(); myCoordsAccessor.setY(0); myCursor.setY(1); myTerminalTextBuffer.addLine(lastLine); } } else { myTerminalTextBuffer.clearAll(); myCoordsAccessor.setX(0); myCoordsAccessor.setY(1); myCursor.setX(0); myCursor.setY(1); } } myBoundedRangeModel.setValue(0); updateScrolling(true); myClientScrollOrigin = myBoundedRangeModel.getValue(); } } @Override public TerminalActionProvider getNextProvider() { return myNextActionProvider; } @Override public void setNextProvider(TerminalActionProvider provider) { myNextActionProvider = provider; } private void processTerminalKeyPressed(KeyEvent e) { if (hasUncommittedChars()) { return; } try { final int keycode = e.getKeyCode(); final char keychar = e.getKeyChar(); // numLock does not change the code sent by keypad VK_DELETE // although it send the char '.' if (keycode == KeyEvent.VK_DELETE && keychar == '.') { myTerminalStarter.sendBytes(new byte[] { '.' }); return; } // CTRL + Space is not handled in KeyEvent; handle it manually else if (keychar == ' ' && (e.getModifiers() & InputEvent.CTRL_MASK) != 0) { myTerminalStarter.sendBytes(new byte[] { Ascii.NUL }); return; } final byte[] code = myTerminalStarter.getCode(keycode, e.getModifiers()); if (code != null) { myTerminalStarter.sendBytes(code); if (mySettingsProvider.scrollToBottomOnTyping() && isCodeThatScrolls(keycode)) { scrollToBottom(); } } else if (Character.isISOControl(keychar)) { // keys filtered out // here will be // processed in // processTerminalKeyTyped processCharacter(keychar, e.getModifiers()); } } catch (final Exception ex) { LOG.error("Error sending pressed key to emulator", ex); } } private void processCharacter(char keychar, int modifiers) { final char[] obuffer; if (mySettingsProvider.altSendsEscape() && (modifiers & InputEvent.ALT_MASK) != 0) { obuffer = new char[] { Ascii.ESC, keychar }; } else { obuffer = new char[] { keychar }; } if (keychar == '`' && (modifiers & InputEvent.META_MASK) != 0) { // Command + backtick is a short-cut on Mac OSX, so we shouldn't // type anything return; } myTerminalStarter.sendString(new String(obuffer)); if (mySettingsProvider.scrollToBottomOnTyping()) { scrollToBottom(); } } private static boolean isCodeThatScrolls(int keycode) { return keycode == KeyEvent.VK_UP || keycode == KeyEvent.VK_DOWN || keycode == KeyEvent.VK_LEFT || keycode == KeyEvent.VK_RIGHT || keycode == KeyEvent.VK_BACK_SPACE || keycode == KeyEvent.VK_INSERT || keycode == KeyEvent.VK_DELETE || keycode == KeyEvent.VK_ENTER || keycode == KeyEvent.VK_HOME || keycode == KeyEvent.VK_END || keycode == KeyEvent.VK_PAGE_UP || keycode == KeyEvent.VK_PAGE_DOWN; } private void processTerminalKeyTyped(KeyEvent e) { if (hasUncommittedChars()) { return; } final char keychar = e.getKeyChar(); if (!Character.isISOControl(keychar)) { // keys filtered out here will // be processed in // processTerminalKeyPressed try { processCharacter(keychar, e.getModifiers()); } catch (final Exception ex) { LOG.error("Error sending typed key to emulator", ex); } } } public class TerminalKeyHandler implements KeyListener { public TerminalKeyHandler() { } public void keyPressed(final KeyEvent e) { if (!TerminalAction.processEvent(TerminalPanel.this, e)) { processTerminalKeyPressed(e); } } public void keyTyped(final KeyEvent e) { processTerminalKeyTyped(e); } // Ignore releases public void keyReleased(KeyEvent e) { } } private void handlePaste() { pasteFromClipboard(false); } private void handlePasteSelection() { pasteFromClipboard(true); } // "unselect" is needed to handle Ctrl+C copy shortcut collision with ^C // signal shortcut private boolean handleCopy(boolean unselect, boolean useSystemSelectionClipboardIfAvailable) { if (mySelection != null) { Pair<Point, Point> points = mySelection .pointsForRun(myTermSize.width); copySelection(points.first, points.second, useSystemSelectionClipboardIfAvailable); if (unselect) { mySelection = null; repaint(); } return true; } return false; } private boolean handleCopy() { return handleCopy(true, false); } private void handleCopyOnSelect() { handleCopy(false, true); } /** * InputMethod implementation For details read * http://docs.oracle.com/javase/7/docs/technotes/guides/imf/api-tutorial.html */ @Override protected void processInputMethodEvent(InputMethodEvent e) { int commitCount = e.getCommittedCharacterCount(); if (commitCount > 0) { myInputMethodUncommittedChars = null; AttributedCharacterIterator text = e.getText(); if (text != null) { StringBuilder sb = new StringBuilder(); // noinspection ForLoopThatDoesntUseLoopVariable for (char c = text.first(); commitCount > 0; c = text .next(), commitCount--) { if (c >= 0x20 && c != 0x7F) { // Hack just like in // javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction sb.append(c); } } if (sb.length() > 0) { myTerminalStarter.sendString(sb.toString()); } } } else { myInputMethodUncommittedChars = uncommittedChars(e.getText()); } } // private static String uncommittedChars( // AttributedCharacterIterator text) { private static String uncommittedChars(AttributedCharacterIterator text) { if (text == null) { return null; } StringBuilder sb = new StringBuilder(); for (char c = text.first(); c != CharacterIterator.DONE; c = text .next()) { if (c >= 0x20 && c != 0x7F) { // Hack just like in // javax.swing.text.DefaultEditorKit.DefaultKeyTypedAction sb.append(c); } } return sb.toString(); } @Override public InputMethodRequests getInputMethodRequests() { return new MyInputMethodRequests(); } private class MyInputMethodRequests implements InputMethodRequests { @Override public Rectangle getTextLocation(TextHitInfo offset) { Rectangle r = new Rectangle( myCursor.getCoordX() * myCharSize.width + getInsetX(), (myCursor.getCoordY() + 1) * myCharSize.height, 0, 0); Point p = TerminalPanel.this.getLocationOnScreen(); r.translate(p.x, p.y); return r; } // @Override public TextHitInfo getLocationOffset(int x, int y) { return null; } @Override public int getInsertPositionOffset() { return 0; } @Override public AttributedCharacterIterator getCommittedText(int beginIndex, int endIndex, AttributedCharacterIterator.Attribute[] attributes) { return null; } @Override public int getCommittedTextLength() { return 0; } // @Override public AttributedCharacterIterator cancelLatestCommittedText( AttributedCharacterIterator.Attribute[] attributes) { return null; } // @Override public AttributedCharacterIterator getSelectedText( AttributedCharacterIterator.Attribute[] attributes) { return null; } } public void dispose() { myRepaintTimer.stop(); } }
if (!isFocusOwner()) { return; } long currentTime = System.currentTimeMillis(); if (cursorShouldChangeBlinkState(currentTime)) { myCursorIsShown = !myCursorIsShown; myLastCursorChange = currentTime; myCursorHasChanged = false; repaint(); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/TerminalTabsImpl.java
TerminalTabsImpl
addChangeListener
class TerminalTabsImpl implements AbstractTabs<JediTermWidget> { protected JTabbedPane myTabbedPane = new JTabbedPane(); @Override public int getTabCount() { return myTabbedPane.getTabCount(); } @Override public void addTab(String name, JediTermWidget terminal) { myTabbedPane.addTab(name, terminal); } @Override public String getTitleAt(int index) { return myTabbedPane.getTitleAt(index); } @Override public int getSelectedIndex() { return myTabbedPane.getSelectedIndex(); } @Override public void setSelectedIndex(int index) { myTabbedPane.setSelectedIndex(index); } @Override public void setTabComponentAt(int index, Component component) { myTabbedPane.setTabComponentAt(index, component); } @Override public int indexOfComponent(Component component) { return myTabbedPane.indexOfComponent(component); } @Override public int indexOfTabComponent(Component component) { return myTabbedPane.indexOfTabComponent(component); } @Override public void removeAll() { myTabbedPane.removeAll(); } @Override public void remove(JediTermWidget terminal) { myTabbedPane.remove(terminal); } @Override public void setTitleAt(int index, String name) { myTabbedPane.setTitleAt(index, name); } @Override public void setSelectedComponent(JediTermWidget terminal) { myTabbedPane.setSelectedComponent(terminal); } @Override public JComponent getComponent() { return myTabbedPane; } @Override public JediTermWidget getComponentAt(int index) { return (JediTermWidget)myTabbedPane.getComponentAt(index); } @Override public void addChangeListener(final TabChangeListener listener) {<FILL_FUNCTION_BODY>} }
myTabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { listener.selectionChanged(); } }); myTabbedPane.addContainerListener(new ContainerListener() { @Override public void componentAdded(ContainerEvent e) { } @Override public void componentRemoved(ContainerEvent e) { if (e.getSource() == myTabbedPane) { listener.tabRemoved(); } } });
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/UIUtil.java
UIUtil
isOracleJvm
class UIUtil { public static final String OS_NAME = System.getProperty("os.name"); public static final String OS_VERSION = System.getProperty("os.version").toLowerCase(); protected static final String _OS_NAME = OS_NAME.toLowerCase(); public static final boolean isWindows = _OS_NAME.startsWith("windows"); public static final boolean isOS2 = _OS_NAME.startsWith("os/2") || _OS_NAME.startsWith("os2"); public static final boolean isMac = _OS_NAME.startsWith("mac"); public static final boolean isLinux = _OS_NAME.startsWith("linux"); public static final boolean isUnix = !isWindows && !isOS2; private static final boolean IS_ORACLE_JVM = isOracleJvm(); public static final String JAVA_RUNTIME_VERSION = System.getProperty("java.runtime.version"); public static boolean isRetina() { if (isJavaVersionAtLeast("1.7.0_40") && IS_ORACLE_JVM) { GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment(); final GraphicsDevice device = env.getDefaultScreenDevice(); try { Field field = device.getClass().getDeclaredField("scale"); if (field != null) { field.setAccessible(true); Object scale = field.get(device); if (scale instanceof Integer && ((Integer)scale).intValue() == 2) { return true; } } } catch (Exception ignore) { } } final Float scaleFactor = (Float)Toolkit.getDefaultToolkit().getDesktopProperty("apple.awt.contentScaleFactor"); if (scaleFactor != null && scaleFactor.intValue() == 2) { return true; } return false; } private static boolean isOracleJvm() {<FILL_FUNCTION_BODY>} public static String getJavaVmVendor() { return System.getProperty("java.vm.vendor"); } public static boolean isJavaVersionAtLeast(String v) { return Util.compareVersionNumbers(JAVA_RUNTIME_VERSION, v) >= 0; } public static void applyRenderingHints(final Graphics g) { Graphics2D g2d = (Graphics2D)g; Toolkit tk = Toolkit.getDefaultToolkit(); //noinspection HardCodedStringLiteral Map map = (Map)tk.getDesktopProperty("awt.font.desktophints"); if (map != null) { g2d.addRenderingHints(map); } } }
final String vendor = getJavaVmVendor(); return vendor != null && Util.containsIgnoreCase(vendor, "Oracle");
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/settings/DefaultSettingsProvider.java
DefaultSettingsProvider
getPasteKeyStrokes
class DefaultSettingsProvider implements SettingsProvider { @Override public KeyStroke[] getNewSessionKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.META_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)}; } @Override public KeyStroke[] getCloseSessionKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.META_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)}; } @Override public KeyStroke[] getCopyKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.META_DOWN_MASK) // CTRL + C is used for signal; use CTRL + SHIFT + C instead : KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)}; } @Override public KeyStroke[] getPasteKeyStrokes() {<FILL_FUNCTION_BODY>} @Override public KeyStroke[] getClearBufferKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_K, InputEvent.META_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_DOWN_MASK)}; } @Override public KeyStroke[] getFindKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.META_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK)}; } @Override public KeyStroke[] getPageUpKeyStrokes() { return new KeyStroke[]{KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, InputEvent.SHIFT_DOWN_MASK)}; } @Override public KeyStroke[] getPageDownKeyStrokes() { return new KeyStroke[]{KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, InputEvent.SHIFT_DOWN_MASK)}; } @Override public KeyStroke[] getLineUpKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.META_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_UP, InputEvent.CTRL_DOWN_MASK)}; } @Override public KeyStroke[] getLineDownKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.META_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, InputEvent.CTRL_DOWN_MASK)}; } @Override public ColorPalette getTerminalColorPalette() { return UIUtil.isWindows ? ColorPalette.WINDOWS_PALETTE : ColorPalette.XTERM_PALETTE; } @Override public Font getTerminalFont() { String fontName; if (UIUtil.isWindows) { fontName = "Consolas"; } else if (UIUtil.isMac) { fontName = "Menlo"; } else { fontName = "Monospaced"; } return new Font(fontName, Font.PLAIN, (int)getTerminalFontSize()); } @Override public float getTerminalFontSize() { return 14; } @Override public float getLineSpace() { return 0; } @Override public TextStyle getDefaultStyle() { return new TextStyle(TerminalColor.BLACK, TerminalColor.WHITE); // return new TextStyle(TerminalColor.WHITE, TerminalColor.rgb(24, 24, 24)); } @Override public TextStyle getSelectionColor() { return new TextStyle(TerminalColor.WHITE, TerminalColor.rgb(82, 109, 165)); } @Override public TextStyle getFoundPatternColor() { return new TextStyle(TerminalColor.BLACK, TerminalColor.rgb(255, 255, 0)); } @Override public TextStyle getHyperlinkColor() { return new TextStyle(TerminalColor.awt(Color.BLUE), TerminalColor.WHITE); } @Override public HyperlinkStyle.HighlightMode getHyperlinkHighlightingMode() { return HyperlinkStyle.HighlightMode.HOVER; } @Override public boolean useInverseSelectionColor() { return true; } @Override public boolean copyOnSelect() { return emulateX11CopyPaste(); } @Override public boolean pasteOnMiddleMouseClick() { return emulateX11CopyPaste(); } @Override public boolean emulateX11CopyPaste() { return false; } @Override public boolean useAntialiasing() { return true; } @Override public int maxRefreshRate() { return 50; } @Override public boolean audibleBell() { return true; } @Override public boolean enableMouseReporting() { return true; } @Override public int caretBlinkingMs() { return 505; } @Override public boolean scrollToBottomOnTyping() { return true; } @Override public boolean DECCompatibilityMode() { return true; } @Override public boolean forceActionOnMouseReporting() { return false; } @Override public int getBufferMaxLinesCount() { return LinesBuffer.DEFAULT_MAX_LINES_COUNT; } @Override public boolean altSendsEscape() { return false; } @Override public boolean ambiguousCharsAreDoubleWidth() { return false; } }
return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.META_DOWN_MASK) // CTRL + V is used for signal; use CTRL + SHIFT + V instead : KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)};
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/ui/settings/DefaultTabbedSettingsProvider.java
DefaultTabbedSettingsProvider
getNextTabKeyStrokes
class DefaultTabbedSettingsProvider extends DefaultSettingsProvider implements TabbedSettingsProvider { @Override public boolean shouldCloseTabOnLogout(TtyConnector ttyConnector) { return true; } @Override public String tabName(TtyConnector ttyConnector, String sessionName) { return sessionName; } @Override public KeyStroke[] getNextTabKeyStrokes() {<FILL_FUNCTION_BODY>} @Override public KeyStroke[] getPreviousTabKeyStrokes() { return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.CTRL_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, InputEvent.ALT_DOWN_MASK)}; } }
return new KeyStroke[]{UIUtil.isMac ? KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.CTRL_DOWN_MASK) : KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, InputEvent.ALT_DOWN_MASK)};
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/util/JTextFieldLimit.java
JTextFieldLimit
insertString
class JTextFieldLimit extends PlainDocument { private int limit; public JTextFieldLimit(int limit) { super(); this.limit = limit; } public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {<FILL_FUNCTION_BODY>} }
if (str == null) return; if ((getLength() + str.length()) <= limit) { super.insertString(offset, str, attr); }
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/util/Pair.java
Pair
equals
class Pair<A, B> { public final A first; public final B second; // public static <A, B> Pair<A, B> create(A first, B second) { return new Pair<A, B>(first, second); } public static <T> T getFirst(Pair<T, ?> pair) { return pair != null ? pair.first : null; } public static <T> T getSecond(Pair<?, T> pair) { return pair != null ? pair.second : null; } @SuppressWarnings("unchecked") private static final Pair EMPTY = create(null, null); @SuppressWarnings("unchecked") public static <A, B> Pair<A, B> empty() { return EMPTY; } public Pair(A first, B second) { this.first = first; this.second = second; } public final A getFirst() { return first; } public final B getSecond() { return second; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} public int hashCode() { int result = first != null ? first.hashCode() : 0; result = 31 * result + (second != null ? second.hashCode() : 0); return result; } public String toString() { return "<" + first + "," + second + ">"; } }
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair pair = (Pair)o; if (first != null ? !first.equals(pair.first) : pair.first != null) return false; if (second != null ? !second.equals(pair.second) : pair.second != null) return false; return true;
subhra74_snowflake
snowflake/muon-jediterm/src/main/java/com/jediterm/terminal/util/Util.java
Util
compareVersionNumbers
class Util { @SuppressWarnings("unchecked") public static <T> T[] copyOf(T[] original, int newLength) { Class<T> type = (Class<T>) original.getClass().getComponentType(); T[] newArr = (T[]) Array.newInstance(type, newLength); System.arraycopy(original, 0, newArr, 0, Math.min(original.length, newLength)); return newArr; } public static int[] copyOf(int[] original, int newLength) { int[] newArr = new int[newLength]; System.arraycopy(original, 0, newArr, 0, Math.min(original.length, newLength)); return newArr; } public static char[] copyOf(char[] original, int newLength) { char[] newArr = new char[newLength]; System.arraycopy(original, 0, newArr, 0, Math.min(original.length, newLength)); return newArr; } public static void bitsetCopy(BitSet src, int srcOffset, BitSet dest, int destOffset, int length) { for (int i = 0; i < length; i++) { dest.set(destOffset + i, src.get(srcOffset + i)); } } public static String trimTrailing(String string) { int index = string.length() - 1; while (index >= 0 && Character.isWhitespace(string.charAt(index))) index--; return string.substring(0, index + 1); } // public static boolean containsIgnoreCase( String where, // String what) { public static boolean containsIgnoreCase( String where, String what) { return indexOfIgnoreCase(where, what, 0) >= 0; } /** * Implementation copied from {@link String#indexOf(String, int)} except * character comparisons made case insensitive */ // public static int indexOfIgnoreCase( String where, // String what, int fromIndex) { public static int indexOfIgnoreCase( String where, String what, int fromIndex) { int targetCount = what.length(); int sourceCount = where.length(); if (fromIndex >= sourceCount) { return targetCount == 0 ? sourceCount : -1; } if (fromIndex < 0) { fromIndex = 0; } if (targetCount == 0) { return fromIndex; } char first = what.charAt(0); int max = sourceCount - targetCount; for (int i = fromIndex; i <= max; i++) { /* Look for first character. */ if (!charsEqualIgnoreCase(where.charAt(i), first)) { while (++i <= max && !charsEqualIgnoreCase(where.charAt(i), first)) ; } /* Found first character, now look at the rest of v2 */ if (i <= max) { int j = i + 1; int end = j + targetCount - 1; for (int k = 1; j < end && charsEqualIgnoreCase(where.charAt(j), what.charAt(k)); j++, k++) ; if (j == end) { /* Found whole string. */ return i; } } } return -1; } public static boolean charsEqualIgnoreCase(char a, char b) { return a == b || toUpperCase(a) == toUpperCase(b) || toLowerCase(a) == toLowerCase(b); } private static char toLowerCase(char b) { return Character.toLowerCase(b); } private static char toUpperCase(char a) { return Character.toUpperCase(a); } // public static int compareVersionNumbers( String v1, String v2) { public static int compareVersionNumbers(String v1, String v2) {<FILL_FUNCTION_BODY>} }
if (v1 == null && v2 == null) { return 0; } if (v1 == null) { return -1; } if (v2 == null) { return 1; } String[] part1 = v1.split("[\\.\\_\\-]"); String[] part2 = v2.split("[\\.\\_\\-]"); int idx = 0; for (; idx < part1.length && idx < part2.length; idx++) { String p1 = part1[idx]; String p2 = part2[idx]; int cmp; if (p1.matches("\\d+") && p2.matches("\\d+")) { cmp = new Integer(p1).compareTo(new Integer(p2)); } else { cmp = part1[idx].compareTo(part2[idx]); } if (cmp != 0) return cmp; } if (part1.length == part2.length) { return 0; } else if (part1.length > idx) { return 1; } else { return -1; }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/SimpleClient.java
SimpleClient
main
class SimpleClient { public static int id = -1; public final static String VERSION = Features.VERSION_1_3_0; public static String serverAddress; public static int port = 1024; public static String protocol = "pb"; private final static String[] serverAddressSource = new String[]{ "https://raw.githubusercontent.com/ainilili/ratel/master/serverlist.json", //Source "https://cdn.jsdelivr.net/gh/ainilili/ratel@master/serverlist.json", //CN CDN "https://raw.fastgit.org/ainilili/ratel/master/serverlist.json", //HongKong CDN "https://cdn.staticaly.com/gh/ainilili/ratel/master/serverlist.json", //Japanese CDN "https://ghproxy.com/https://raw.githubusercontent.com/ainilili/ratel/master/serverlist.json", //Korea CDN "https://gitee.com/ainilili/ratel/raw/master/serverlist.json" //CN Gitee }; public static void main(String[] args) throws InterruptedException, IOException, URISyntaxException {<FILL_FUNCTION_BODY>} private static List<String> getServerAddressList() { for (String serverAddressSource : serverAddressSource) { try { String serverInfo = StreamUtils.convertToString(new URL(serverAddressSource)); return Noson.convert(serverInfo, new NoType<List<String>>() {}); } catch (IOException e) { SimplePrinter.printNotice("Try connected " + serverAddressSource + " failed: " + e.getMessage()); } } return null; } }
if (args != null && args.length > 0) { for (int index = 0; index < args.length; index = index + 2) { if (index + 1 < args.length) { if (args[index].equalsIgnoreCase("-p") || args[index].equalsIgnoreCase("-port")) { port = Integer.parseInt(args[index + 1]); } if (args[index].equalsIgnoreCase("-h") || args[index].equalsIgnoreCase("-host")) { serverAddress = args[index + 1]; } if (args[index].equalsIgnoreCase("-ptl") || args[index].equalsIgnoreCase("-protocol")) { protocol = args[index + 1]; } } } } if (serverAddress == null) { List<String> serverAddressList = getServerAddressList(); if (serverAddressList == null || serverAddressList.size() == 0) { throw new RuntimeException("Please use '-host' to setting server address."); } SimplePrinter.printNotice("Please select a server:"); for (int i = 0; i < serverAddressList.size(); i++) { SimplePrinter.printNotice((i + 1) + ". " + serverAddressList.get(i)); } int serverPick = Integer.parseInt(SimpleWriter.write(User.INSTANCE.getNickname(), "option")); while (serverPick < 1 || serverPick > serverAddressList.size()) { try { SimplePrinter.printNotice("The server address does not exist!"); serverPick = Integer.parseInt(SimpleWriter.write(User.INSTANCE.getNickname(), "option")); } catch (NumberFormatException ignore) {} } serverAddress = serverAddressList.get(serverPick - 1); String[] elements = serverAddress.split(":"); serverAddress = elements[0]; port = Integer.parseInt(elements[1]); } if (Objects.equals(protocol, "pb")) { new ProtobufProxy().connect(serverAddress, port); } else if (Objects.equals(protocol, "ws")) { new WebsocketProxy().connect(serverAddress, port + 1); } else { throw new UnsupportedOperationException("Unsupported protocol " + protocol); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener.java
ClientEventListener
initLastSellInfo
class ClientEventListener { public abstract void call(Channel channel, String data); public final static Map<ClientEventCode, ClientEventListener> LISTENER_MAP = new HashMap<>(); private final static String LISTENER_PREFIX = "org.nico.ratel.landlords.client.event.ClientEventListener_"; protected static List<Poker> lastPokers = null; protected static String lastSellClientNickname = null; protected static String lastSellClientType = null; protected static void initLastSellInfo() {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") public static ClientEventListener get(ClientEventCode code) { ClientEventListener listener; try { if (ClientEventListener.LISTENER_MAP.containsKey(code)) { listener = ClientEventListener.LISTENER_MAP.get(code); } else { String eventListener = LISTENER_PREFIX + code.name().toUpperCase(Locale.ROOT); Class<ClientEventListener> listenerClass = (Class<ClientEventListener>) Class.forName(eventListener); listener = listenerClass.newInstance(); ClientEventListener.LISTENER_MAP.put(code, listener); } return listener; } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; } protected ChannelFuture pushToServer(Channel channel, ServerEventCode code, String datas) { return ChannelUtils.pushToServer(channel, code, datas); } protected ChannelFuture pushToServer(Channel channel, ServerEventCode code) { return pushToServer(channel, code, null); } }
lastPokers = null; lastSellClientNickname = null; lastSellClientType = null;
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_CLIENT_CONNECT.java
ClientEventListener_CODE_CLIENT_CONNECT
call
class ClientEventListener_CODE_CLIENT_CONNECT extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("Connected to server. Welcome to ratel!"); SimpleClient.id = Integer.parseInt(data); Map<String, Object> infos = new HashMap<>(); infos.put("version", SimpleClient.VERSION); pushToServer(channel, ServerEventCode.CODE_CLIENT_INFO_SET, Noson.reversal(infos));
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_CLIENT_EXIT.java
ClientEventListener_CODE_CLIENT_EXIT
call
class ClientEventListener_CODE_CLIENT_EXIT extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); Integer exitClientId = (Integer) map.get("exitClientId"); String role; if (exitClientId == SimpleClient.id) { role = "You"; } else { role = String.valueOf(map.get("exitClientNickname")); } SimplePrinter.printNotice(role + " left the room. Room disbanded!\n"); get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_CLIENT_KICK.java
ClientEventListener_CODE_CLIENT_KICK
call
class ClientEventListener_CODE_CLIENT_KICK extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("You have been kicked from the room for being idle.\n"); get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_CLIENT_NICKNAME_SET.java
ClientEventListener_CODE_CLIENT_NICKNAME_SET
call
class ClientEventListener_CODE_CLIENT_NICKNAME_SET extends ClientEventListener { public static final int NICKNAME_MAX_LENGTH = 10; @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
// If it is not the first time that the user is prompted to enter nickname // If first time, data = null or "" otherwise not empty if (StringUtils.isNotBlank(data)) { Map<String, Object> dataMap = MapHelper.parser(data); if (dataMap.containsKey("invalidLength")) { SimplePrinter.printNotice("Your nickname has invalid length: " + dataMap.get("invalidLength")); } } SimplePrinter.printNotice("Please set your nickname (upto " + NICKNAME_MAX_LENGTH + " characters)"); String nickname = SimpleWriter.write(User.INSTANCE.getNickname(), "nickname"); // If the length of nickname is more that NICKNAME_MAX_LENGTH if (nickname.trim().length() > NICKNAME_MAX_LENGTH) { String result = MapHelper.newInstance().put("invalidLength", nickname.trim().length()).json(); get(ClientEventCode.CODE_CLIENT_NICKNAME_SET).call(channel, result); } else { pushToServer(channel, ServerEventCode.CODE_CLIENT_NICKNAME_SET, nickname); User.INSTANCE.setNickname(nickname); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_LANDLORD_CONFIRM.java
ClientEventListener_CODE_GAME_LANDLORD_CONFIRM
call
class ClientEventListener_CODE_GAME_LANDLORD_CONFIRM extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); String landlordNickname = String.valueOf(map.get("landlordNickname")); int baseScore = (Integer) map.get("baseScore"); String baseScoreString; if (baseScore == 1) { baseScoreString = "1 score"; } else { baseScoreString = baseScore + " scores"; } SimplePrinter.printNotice(landlordNickname + " has become the landlord with " + baseScoreString + " and gotten three extra cards"); List<Poker> additionalPokers = Noson.convert(map.get("additionalPokers"), new NoType<List<Poker>>() {}); SimplePrinter.printPokers(additionalPokers); pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_REDIRECT);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_LANDLORD_ELECT.java
ClientEventListener_CODE_GAME_LANDLORD_ELECT
call
class ClientEventListener_CODE_GAME_LANDLORD_ELECT extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); int turnClientId = (int) map.get("nextClientId"); int highestScore = (int) map.get("highestScore"); if (map.containsKey("preClientNickname")) { if (highestScore != 0 && map.get("preClientId") == map.get("currentLandlordId")) { SimplePrinter.printNotice(map.get("preClientNickname") + " robs the landlord with " + highestScore + " score" + (highestScore == 1 ? "" : "s") + "!"); } else { SimplePrinter.printNotice(map.get("preClientNickname") + " don't rob the landlord!"); } } if (turnClientId != SimpleClient.id) { SimplePrinter.printNotice("It's " + map.get("nextClientNickname") + "'s turn. Please wait patiently for his/her confirmation !"); } else { String message = "It's your turn. What score do you want to rob the landlord? [0"; for(int i = highestScore + 1; i <= 3; ++i) { message = message + "/" + i; } message = message + "] (enter [exit|e] to exit current room)"; SimplePrinter.printNotice(message); String line = SimpleWriter.write("getScore"); if (!line.equalsIgnoreCase("exit") && !line.equalsIgnoreCase("e")) { try { int currentScore = Integer.parseInt(line); if (currentScore <= highestScore && currentScore != 0 || currentScore > 3) { SimplePrinter.printNotice("Invalid options"); this.call(channel, data); return; } String result; if (currentScore > highestScore) { result = MapHelper.newInstance() .put("highestScore", currentScore) .put("currentLandlordId", SimpleClient.id) .json(); } else if (map.containsKey("currentLandlordId")) { result = MapHelper.newInstance() .put("highestScore", highestScore) .put("currentLandlordId", (int) map.get("currentLandlordId")) .json(); } else { result = MapHelper.newInstance() .put("highestScore", 0) .json(); } this.pushToServer(channel, ServerEventCode.CODE_GAME_LANDLORD_ELECT, result); } catch (Exception e) { SimplePrinter.printNotice("Invalid options"); this.call(channel, data); } } else { this.pushToServer(channel, ServerEventCode.CODE_CLIENT_EXIT); } }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_OVER.java
ClientEventListener_CODE_GAME_OVER
call
class ClientEventListener_CODE_GAME_OVER extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice("\nPlayer " + map.get("winnerNickname") + "[" + map.get("winnerType") + "]" + " won the game"); if (map.containsKey("scores")){ List<Map<String, Object>> scores = Noson.convert(map.get("scores"), new NoType<List<Map<String, Object>>>() {}); for (Map<String, Object> score : scores) { if (! Objects.equals(score.get("clientId"), SimpleClient.id)) { SimplePrinter.printNotice(score.get("nickName").toString() + "'s rest poker is:"); SimplePrinter.printPokers(Noson.convert(score.get("pokers"), new NoType<List<Poker>>() {})); } } SimplePrinter.printNotice("\n"); // print score for (Map<String, Object> score : scores) { String scoreInc = score.get("scoreInc").toString(); String scoreTotal = score.get("score").toString(); if (SimpleClient.id != (int) score.get("clientId")) { SimplePrinter.printNotice(score.get("nickName").toString() + "'s score is " + scoreInc + ", total score is " + scoreTotal); } else { SimplePrinter.printNotice("your score is " + scoreInc + ", total score is " + scoreTotal); } } ClientEventListener_CODE_GAME_READY.gameReady(channel); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY.java
ClientEventListener_CODE_GAME_POKER_PLAY
call
class ClientEventListener_CODE_GAME_POKER_PLAY extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice("It's your turn to play, your cards are as follows: "); List<Poker> pokers = Noson.convert(map.get("pokers"), new NoType<List<Poker>>() { }); SimplePrinter.printPokers(pokers); SimplePrinter.printNotice("Last cards are"); SimplePrinter.printNotice(map.containsKey("lastPokers")?map.get("lastPokers").toString():""); SimplePrinter.printNotice("Please enter the combination you came up with (enter [exit|e] to exit current room, enter [pass|p] to jump current round, enter [view|v] to show all valid combinations.)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "combination"); if (line == null) { SimplePrinter.printNotice("Invalid enter"); call(channel, data); } else { if (line.equalsIgnoreCase("pass") || line.equalsIgnoreCase("p")) { pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_PASS); } else if (line.equalsIgnoreCase("exit") || line.equalsIgnoreCase("e")) { pushToServer(channel, ServerEventCode.CODE_CLIENT_EXIT); } else if (line.equalsIgnoreCase("view") || line.equalsIgnoreCase("v")) { if (!map.containsKey("lastSellPokers") || !map.containsKey("lastSellClientId")) { SimplePrinter.printNotice("Current server version unsupport this feature, need more than v1.2.4."); call(channel, data); return; } Object lastSellPokersObj = map.get("lastSellPokers"); if (lastSellPokersObj == null || Integer.valueOf(SimpleClient.id).equals(map.get("lastSellClientId"))) { SimplePrinter.printNotice("Up to you !"); call(channel, data); return; } else { List<Poker> lastSellPokers = Noson.convert(lastSellPokersObj, new NoType<List<Poker>>() {}); List<PokerSell> sells = PokerHelper.validSells(PokerHelper.checkPokerType(lastSellPokers), pokers); if (sells.size() == 0) { SimplePrinter.printNotice("It is a pity that, there is no winning combination..."); call(channel, data); return; } for (int i = 0; i < sells.size(); i++) { SimplePrinter.printNotice(i + 1 + ". " + PokerHelper.textOnlyNoType(sells.get(i).getSellPokers())); } while (true) { SimplePrinter.printNotice("You can enter index to choose anyone.(enter [back|b] to go back.)"); line = SimpleWriter.write(User.INSTANCE.getNickname(), "choose"); if (line.equalsIgnoreCase("back") || line.equalsIgnoreCase("b")) { call(channel, data); return; } else { try { int choose = Integer.valueOf(line); if (choose < 1 || choose > sells.size()) { SimplePrinter.printNotice("The input number must be in the range of 1 to " + sells.size() + "."); } else { List<Poker> choosePokers = sells.get(choose - 1).getSellPokers(); List<Character> options = new ArrayList<>(); for (Poker poker : choosePokers) { options.add(poker.getLevel().getAlias()[0]); } pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY, Noson.reversal(options.toArray(new Character[]{}))); break; } } catch (NumberFormatException e) { SimplePrinter.printNotice("Please input a number."); } } } } // PokerHelper.validSells(lastPokerSell, pokers); } else { String[] strs = line.split(" "); List<Character> options = new ArrayList<>(); boolean access = true; for (int index = 0; index < strs.length; index++) { String str = strs[index]; for (char c : str.toCharArray()) { if (c == ' ' || c == '\t') { } else { if (!PokerLevel.aliasContains(c)) { access = false; break; } else { options.add(c); } } } } if (access) { pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY, Noson.reversal(options.toArray(new Character[]{}))); } else { SimplePrinter.printNotice("Invalid enter"); if (lastPokers != null) { SimplePrinter.printNotice(lastSellClientNickname + "[" + lastSellClientType + "] played:"); SimplePrinter.printPokers(lastPokers); } call(channel, data); } } }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_CANT_PASS.java
ClientEventListener_CODE_GAME_POKER_PLAY_CANT_PASS
call
class ClientEventListener_CODE_GAME_POKER_PLAY_CANT_PASS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("You played the previous card, so you can't pass."); pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_REDIRECT);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_INVALID.java
ClientEventListener_CODE_GAME_POKER_PLAY_INVALID
call
class ClientEventListener_CODE_GAME_POKER_PLAY_INVALID extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("This combination is invalid."); if(lastPokers != null) { SimplePrinter.printNotice(lastSellClientNickname + "[" + lastSellClientType + "] played:"); SimplePrinter.printPokers(lastPokers); } pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_REDIRECT);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_LESS.java
ClientEventListener_CODE_GAME_POKER_PLAY_LESS
call
class ClientEventListener_CODE_GAME_POKER_PLAY_LESS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("Your combination has lower rank than the previous. You cannot play this combination!"); if(lastPokers != null) { SimplePrinter.printNotice(lastSellClientNickname + "[" + lastSellClientType + "] played:"); SimplePrinter.printPokers(lastPokers); } pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_REDIRECT);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_MISMATCH.java
ClientEventListener_CODE_GAME_POKER_PLAY_MISMATCH
call
class ClientEventListener_CODE_GAME_POKER_PLAY_MISMATCH extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice("Your combination is " + map.get("playType") + " (" + map.get("playCount") + "), but the previous combination is " + map.get("preType") + " (" + map.get("preCount") + "). Mismatch!"); if(lastPokers != null) { SimplePrinter.printNotice(lastSellClientNickname + "[" + lastSellClientType + "] played:"); SimplePrinter.printPokers(lastPokers); } pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_REDIRECT);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_ORDER_ERROR.java
ClientEventListener_CODE_GAME_POKER_PLAY_ORDER_ERROR
call
class ClientEventListener_CODE_GAME_POKER_PLAY_ORDER_ERROR extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("It is not your turn yet. Please wait for other players!");
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_PASS.java
ClientEventListener_CODE_GAME_POKER_PLAY_PASS
call
class ClientEventListener_CODE_GAME_POKER_PLAY_PASS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice(map.get("clientNickname") + " passed. It is now " + map.get("nextClientNickname") + "'s turn."); int turnClientId = (int) map.get("nextClientId"); if (SimpleClient.id == turnClientId) { pushToServer(channel, ServerEventCode.CODE_GAME_POKER_PLAY_REDIRECT); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_POKER_PLAY_REDIRECT.java
ClientEventListener_CODE_GAME_POKER_PLAY_REDIRECT
call
class ClientEventListener_CODE_GAME_POKER_PLAY_REDIRECT extends ClientEventListener { private static String[] choose = new String[]{"UP", "DOWN"}; private static String format = "\n[%-4s] %-" + NICKNAME_MAX_LENGTH + "s surplus %-2s [%-8s]"; @SuppressWarnings("unchecked") @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); int sellClientId = (int) map.get("sellClientId"); List<Map<String, Object>> clientInfos = (List<Map<String, Object>>) map.get("clientInfos"); for (int index = 0; index < 2; index++) { for (Map<String, Object> clientInfo : clientInfos) { String position = (String) clientInfo.get("position"); if (position.equalsIgnoreCase(choose[index])) { FormatPrinter.printNotice(format, clientInfo.get("position"), clientInfo.get("clientNickname"), clientInfo.get("surplus"), clientInfo.get("type")); } } } SimplePrinter.printNotice(""); if (sellClientId == SimpleClient.id) { get(ClientEventCode.CODE_GAME_POKER_PLAY).call(channel, data); } else { SimplePrinter.printNotice("It is " + map.get("sellClientNickname") + "'s turn. Please wait for him to play his cards."); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_READY.java
ClientEventListener_CODE_GAME_READY
call
class ClientEventListener_CODE_GAME_READY extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} static void gameReady(Channel channel) { SimplePrinter.printNotice("\nDo you want to continue the game? [Y/N]"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "notReady"); if (line.equals("Y") || line.equals("y")) { ChannelUtils.pushToServer(channel, ServerEventCode.CODE_GAME_READY, ""); return; } ChannelUtils.pushToServer(channel, ServerEventCode.CODE_CLIENT_EXIT, ""); } }
Map<String, Object> map = MapHelper.parser(data); if (SimpleClient.id == (int) map.get("clientId")) { SimplePrinter.printNotice("you are ready to play game."); return; } SimplePrinter.printNotice(map.get("clientNickName").toString() + " is ready to play game.");
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_STARTING.java
ClientEventListener_CODE_GAME_STARTING
call
class ClientEventListener_CODE_GAME_STARTING extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice("Game starting!"); List<Poker> pokers = Noson.convert(map.get("pokers"), new NoType<List<Poker>>() {}); SimplePrinter.printNotice(""); SimplePrinter.printNotice("Your cards are"); SimplePrinter.printPokers(pokers); SimplePrinter.printNotice("Last cards are"); SimplePrinter.printNotice(map.containsKey("lastPokers")?map.get("lastPokers").toString():""); get(ClientEventCode.CODE_GAME_LANDLORD_ELECT).call(channel, data);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_WATCH.java
ClientEventListener_CODE_GAME_WATCH
call
class ClientEventListener_CODE_GAME_WATCH extends ClientEventListener { @Override public void call(Channel channel, String wrapData) {<FILL_FUNCTION_BODY>} private void printJoinPlayerInfo(Object rawData) { printNoticeWithTime("Player [" + rawData + "] joined the room"); } private void printGameStartInfo(Object rawData) { Map<String, Object> map = MapHelper.parser(rawData.toString()); printNoticeWithTime("Game starting"); printNoticeWithTime("Player1 : " + map.get("player1")); printNoticeWithTime("Player2 : " + map.get("player2")); printNoticeWithTime("Player3 : " + map.get("player3")); } private void printRobLandlord(Object rawData) { printNoticeWithTime("Player [" + rawData + "] didn't choose to become the landlord."); } private void printConfirmLandlord(Object rawData) { Map<String, Object> map = MapHelper.parser(rawData.toString()); printNoticeWithTime("Player [" + map.get("landlord") + "] has become the landlord and gotten three extra cards:"); SimplePrinter.printPokers(Noson.convert(map.get("additionalPokers"), new NoType<List<Poker>>() {})); } private void printPlayPokers(Object rawData) { Map<String, Object> map = MapHelper.parser(rawData.toString()); printNoticeWithTime("Player [" + map.get("clientNickname") + "] played:"); SimplePrinter.printPokers(Noson.convert(map.get("pokers"), new NoType<List<Poker>>() {})); } private void printPlayPass(Object rawData) { printNoticeWithTime("Player [" + rawData + "] : passed"); } private void printPlayerExit(Object rawData, Channel channel) { printNoticeWithTime("Player [" + rawData + "] left the room"); quitWatch(channel); } private void quitWatch(Channel channel) { printNoticeWithTime("This room will be closed!"); printNoticeWithTime("Spectating ended. Bye."); SimplePrinter.printNotice(""); SimplePrinter.printNotice(""); // 修改玩家是否观战状态 User.INSTANCE.setWatching(false); // 退出watch展示 get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, ""); } private void printGameResult(Object rawData, Channel channel) { Map<String, Object> map = MapHelper.parser(rawData.toString()); printNoticeWithTime("Player [" + map.get("winnerNickname") + "](" + map.get("winnerType") + ") won the game."); } private void printKickInfo(Object rawData) { printNoticeWithTime("Player [" + rawData + "] has been kicked out for being idle."); } private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private void printNoticeWithTime(String notice) { String msg = FORMATTER.format(LocalDateTime.now()) + " " + notice; SimplePrinter.printNotice(msg); } }
// 退出观战模式后不处理观战请求 if (!User.INSTANCE.isWatching()) { return; } Map<String, Object> wrapMap = MapHelper.parser(wrapData); ClientEventCode rawCode = ClientEventCode.valueOf(wrapMap.get("code").toString()); Object rawData = wrapMap.get("data"); switch (rawCode) { case CODE_ROOM_JOIN_SUCCESS: printJoinPlayerInfo(rawData); break; // 游戏开始 case CODE_GAME_STARTING: printGameStartInfo(rawData); break; // 抢地主 case CODE_GAME_LANDLORD_ELECT: printRobLandlord(rawData); break; // 地主确认 case CODE_GAME_LANDLORD_CONFIRM: printConfirmLandlord(rawData); break; // 出牌 case CODE_SHOW_POKERS: printPlayPokers(rawData); break; // 不出(过) case CODE_GAME_POKER_PLAY_PASS: printPlayPass(rawData); break; // 玩家退出(此时可以退出观战,修改User.isWatching状态) case CODE_CLIENT_EXIT: printPlayerExit(rawData, channel); break; // 玩家被提出房间 case CODE_CLIENT_KICK: printKickInfo(rawData); break; // 游戏结束(此时可以退出观战,修改User.isWatching状态) case CODE_GAME_OVER: printGameResult(rawData, channel); break; // 其他事件忽略 default: break; }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_GAME_WATCH_SUCCESSFUL.java
ClientEventListener_CODE_GAME_WATCH_SUCCESSFUL
quitWatch
class ClientEventListener_CODE_GAME_WATCH_SUCCESSFUL extends ClientEventListener { private static final String WATCH_SUCCESSFUL_TIPS = " \n" + "+------------------------------------------------\n" + "|You are already watching the game. \n" + "|Room owner: %s. Room current status: %s.\n" + "+------------------------------------------------\n" + "(Hint: enter [exit|e] to exit.) \n" + " "; @Override public void call(Channel channel, String data) { // 修改User.isWatching状态 // Edit User.isWatching User.INSTANCE.setWatching(true); // 进入观战提示 // Enter spectator mode Map<String, Object> map = MapHelper.parser(data); SimplePrinter.printNotice(String.format(WATCH_SUCCESSFUL_TIPS, map.get("owner"), map.get("status"))); // 监听输入用于退出 // Listen enter event to exit spectator mode new Thread(() -> registerExitEvent(channel), "exit-spectator-input-thread").start(); } private void registerExitEvent(Channel channel) { String enter = SimpleWriter.write(); if ("exit".equalsIgnoreCase(enter) || "e".equalsIgnoreCase(enter)) { quitWatch(channel); return; } printCommandUsage(); registerExitEvent(channel); } private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private void quitWatch(Channel channel) {<FILL_FUNCTION_BODY>} private void printCommandUsage() { SimplePrinter.printNotice("Enter [exit|e] to exit"); } }
SimplePrinter.printNotice(FORMATTER.format(LocalDateTime.now()) + " Spectating ended. Bye."); SimplePrinter.printNotice(""); SimplePrinter.printNotice(""); // 修改玩家是否观战状态 User.INSTANCE.setWatching(false); // 退出观战模式 pushToServer(channel, ServerEventCode.CODE_GAME_WATCH_EXIT); get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, "");
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_PVE_DIFFICULTY_NOT_SUPPORT.java
ClientEventListener_CODE_PVE_DIFFICULTY_NOT_SUPPORT
call
class ClientEventListener_CODE_PVE_DIFFICULTY_NOT_SUPPORT extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("The current difficulty is not supported, please pay attention to the following.\n"); get(ClientEventCode.CODE_SHOW_OPTIONS_PVE).call(channel, data);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_ROOM_CREATE_SUCCESS.java
ClientEventListener_CODE_ROOM_CREATE_SUCCESS
call
class ClientEventListener_CODE_ROOM_CREATE_SUCCESS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Room room = Noson.convert(data, Room.class); initLastSellInfo(); SimplePrinter.printNotice("You have created a room with id " + room.getId()); SimplePrinter.printNotice("Please wait for other players to join !");
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_ROOM_JOIN_FAIL_BY_FULL.java
ClientEventListener_CODE_ROOM_JOIN_FAIL_BY_FULL
call
class ClientEventListener_CODE_ROOM_JOIN_FAIL_BY_FULL extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> dataMap = MapHelper.parser(data); SimplePrinter.printNotice("Join room failed. Room " + dataMap.get("roomId") + " is full!"); ClientEventListener.get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_ROOM_JOIN_FAIL_BY_INEXIST.java
ClientEventListener_CODE_ROOM_JOIN_FAIL_BY_INEXIST
call
class ClientEventListener_CODE_ROOM_JOIN_FAIL_BY_INEXIST extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> dataMap = MapHelper.parser(data); SimplePrinter.printNotice("Join room failed. Room " + dataMap.get("roomId") + " doesn't exist!"); ClientEventListener.get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data);
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_ROOM_JOIN_SUCCESS.java
ClientEventListener_CODE_ROOM_JOIN_SUCCESS
call
class ClientEventListener_CODE_ROOM_JOIN_SUCCESS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); initLastSellInfo(); int joinClientId = (int) map.get("clientId"); if (SimpleClient.id == joinClientId) { SimplePrinter.printNotice("You have joined room:" + map.get("roomId") + ". There are " + map.get("roomClientCount") + " players in the room now."); SimplePrinter.printNotice("Please wait for other players to join. The game would start at three players!"); } else { SimplePrinter.printNotice(map.get("clientNickname") + " joined room, there are currently " + map.get("roomClientCount") + " in the room."); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_OPTIONS.java
ClientEventListener_CODE_SHOW_OPTIONS
call
class ClientEventListener_CODE_SHOW_OPTIONS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("Options: "); SimplePrinter.printNotice("1. PvP"); SimplePrinter.printNotice("2. PvE"); SimplePrinter.printNotice("3. Settings"); SimplePrinter.printNotice("Please select an option above (enter [exit|e] to log out)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "selection"); if(line.equalsIgnoreCase("exit") || line.equalsIgnoreCase("e")) { System.exit(0); } else { int choose = OptionsUtils.getOptions(line); if (choose == 1) { get(ClientEventCode.CODE_SHOW_OPTIONS_PVP).call(channel, data); } else if (choose == 2) { get(ClientEventCode.CODE_SHOW_OPTIONS_PVE).call(channel, data); } else if (choose == 3) { get(ClientEventCode.CODE_SHOW_OPTIONS_SETTING).call(channel, data); } else { SimplePrinter.printNotice("Invalid option, please choose again:"); call(channel, data); } }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_OPTIONS_PVE.java
ClientEventListener_CODE_SHOW_OPTIONS_PVE
call
class ClientEventListener_CODE_SHOW_OPTIONS_PVE extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("PVE: "); SimplePrinter.printNotice("1. Easy Mode"); SimplePrinter.printNotice("2. Medium Mode"); SimplePrinter.printNotice("3. Hard Mode"); SimplePrinter.printNotice("Please select an option above (enter [back|b] to return to options list)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "pve"); if(line.equalsIgnoreCase("back") || line.equalsIgnoreCase("b")) { get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data); return; } int choose = OptionsUtils.getOptions(line); if (choose < 0 || choose >= 4) { SimplePrinter.printNotice("Invalid option, please choose again:"); call(channel, data); return; } initLastSellInfo(); pushToServer(channel, ServerEventCode.CODE_ROOM_CREATE_PVE, String.valueOf(choose));
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_OPTIONS_PVP.java
ClientEventListener_CODE_SHOW_OPTIONS_PVP
call
class ClientEventListener_CODE_SHOW_OPTIONS_PVP extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} private void parseInvalid(Channel channel, String data) { SimplePrinter.printNotice("Invalid options, please choose again:"); call(channel, data); } private void handleJoinRoom(Channel channel, String data) { handleJoinRoom(channel, data, false); } private void handleJoinRoom(Channel channel, String data, Boolean watchMode) { String notice = String.format("Please enter the room id you want to %s (enter [back|b] return options list)", watchMode ? "spectate" : "join"); SimplePrinter.printNotice(notice); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "roomid"); if (line == null) { parseInvalid(channel, data); return; } if (line.equalsIgnoreCase("BACK") || line.equalsIgnoreCase("b")) { call(channel, data); return; } int option = OptionsUtils.getOptions(line); if (option < 1) { parseInvalid(channel, data); return; } pushToServer(channel, watchMode? ServerEventCode.CODE_GAME_WATCH : ServerEventCode.CODE_ROOM_JOIN, String.valueOf(option)); } }
SimplePrinter.printNotice("PVP: "); SimplePrinter.printNotice("1. Create Room"); SimplePrinter.printNotice("2. Room List"); SimplePrinter.printNotice("3. Join Room"); SimplePrinter.printNotice("4. Spectate Game"); SimplePrinter.printNotice("Please select an option above (enter [back|b] to return to options list)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "pvp"); if (line == null) { SimplePrinter.printNotice("Invalid options, please choose again:"); call(channel, data); return; } if (line.equalsIgnoreCase("BACK") || line.equalsIgnoreCase("b")) { get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data); return; } int choose = OptionsUtils.getOptions(line); switch (choose) { case 1: pushToServer(channel, ServerEventCode.CODE_ROOM_CREATE, null); break; case 2: pushToServer(channel, ServerEventCode.CODE_GET_ROOMS, null); break; case 3: handleJoinRoom(channel, data); break; case 4: handleJoinRoom(channel, data, true); break; default: SimplePrinter.printNotice("Invalid option, please choose again:"); call(channel, data); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_OPTIONS_SETTING.java
ClientEventListener_CODE_SHOW_OPTIONS_SETTING
call
class ClientEventListener_CODE_SHOW_OPTIONS_SETTING extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
SimplePrinter.printNotice("Setting: "); SimplePrinter.printNotice("1. Card with shape edges (Default)"); SimplePrinter.printNotice("2. Card with rounded edges"); SimplePrinter.printNotice("3. Text Only with types"); SimplePrinter.printNotice("4. Text Only without types"); SimplePrinter.printNotice("5. Unicode Cards"); SimplePrinter.printNotice("Please select an option above (enter [BACK] to return to options list)"); String line = SimpleWriter.write(User.INSTANCE.getNickname(), "setting"); if (line.equalsIgnoreCase("BACK")) { get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data); } else { int choose = OptionsUtils.getOptions(line); if (choose >= 1 && choose <= 5) { PokerHelper.pokerPrinterType = choose - 1; get(ClientEventCode.CODE_SHOW_OPTIONS).call(channel, data); } else { SimplePrinter.printNotice("Invalid setting, please choose again:"); call(channel, data); } }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_POKERS.java
ClientEventListener_CODE_SHOW_POKERS
call
class ClientEventListener_CODE_SHOW_POKERS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
Map<String, Object> map = MapHelper.parser(data); lastSellClientNickname = (String) map.get("clientNickname"); lastSellClientType = (String) map.get("clientType"); SimplePrinter.printNotice(lastSellClientNickname + "[" + lastSellClientType + "] played:"); lastPokers = Noson.convert(map.get("pokers"), new NoType<List<Poker>>() {}); SimplePrinter.printPokers(lastPokers); if (map.containsKey("sellClientNickname")) { SimplePrinter.printNotice("Next player is " + map.get("sellClientNickname") + ". Please wait for him to play his combination."); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/event/ClientEventListener_CODE_SHOW_ROOMS.java
ClientEventListener_CODE_SHOW_ROOMS
call
class ClientEventListener_CODE_SHOW_ROOMS extends ClientEventListener { @Override public void call(Channel channel, String data) {<FILL_FUNCTION_BODY>} }
List<Map<String, Object>> roomList = Noson.convert(data, new NoType<List<Map<String, Object>>>() {}); if (roomList != null && !roomList.isEmpty()) { // "COUNT" begins after NICKNAME_MAX_LENGTH characters. The dash means that the string is left-justified. String format = "#\t%s\t|\t%-" + NICKNAME_MAX_LENGTH + "s\t|\t%-6s\t|\t%-6s\t#\n"; FormatPrinter.printNotice(format, "ID", "OWNER", "COUNT", "TYPE"); for (Map<String, Object> room : roomList) { FormatPrinter.printNotice(format, room.get("roomId"), room.get("roomOwner"), room.get("roomClientCount"), room.get("roomType")); } SimplePrinter.printNotice(""); get(ClientEventCode.CODE_SHOW_OPTIONS_PVP).call(channel, data); } else { SimplePrinter.printNotice("No available room. Please create a room!"); get(ClientEventCode.CODE_SHOW_OPTIONS_PVP).call(channel, data); }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/handler/ProtobufTransferHandler.java
ProtobufTransferHandler
channelRead
class ProtobufTransferHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) {<FILL_FUNCTION_BODY>} @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.WRITER_IDLE) { ChannelUtils.pushToServer(ctx.channel(), ServerEventCode.CODE_CLIENT_HEAD_BEAT, "heartbeat"); } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { if (cause instanceof java.io.IOException) { SimplePrinter.printNotice("The network is not good or did not operate for a long time, has been offline"); System.exit(0); } } }
if (msg instanceof ClientTransferDataProtoc) { ClientTransferDataProtoc clientTransferData = (ClientTransferDataProtoc) msg; if (!clientTransferData.getInfo().isEmpty()) { SimplePrinter.printNotice(clientTransferData.getInfo()); } ClientEventCode code = ClientEventCode.valueOf(clientTransferData.getCode()); if (User.INSTANCE.isWatching()) { Map<String, Object> wrapMap = new HashMap<>(3); wrapMap.put("code", code); wrapMap.put("data", clientTransferData.getData()); ClientEventListener.get(ClientEventCode.CODE_GAME_WATCH).call(ctx.channel(), Noson.reversal(wrapMap)); } else { ClientEventListener.get(code).call(ctx.channel(), clientTransferData.getData()); } }
ainilili_ratel
ratel/landlords-client/src/main/java/org/nico/ratel/landlords/client/handler/WebsocketTransferHandler.java
WebsocketTransferHandler
userEventTriggered
class WebsocketTransferHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) { Msg msg = JsonUtils.fromJson(frame.text(), Msg.class); if(msg.getInfo() != null && ! msg.getInfo().isEmpty()) { SimplePrinter.printNotice(msg.getInfo()); } ClientEventCode code = ClientEventCode.valueOf(msg.getCode()); if (User.INSTANCE.isWatching()) { Map<String, Object> wrapMap = new HashMap<>(3); wrapMap.put("code", code); wrapMap.put("data", msg.getData()); ClientEventListener.get(ClientEventCode.CODE_GAME_WATCH).call(ctx.channel(), JsonUtils.toJson(wrapMap)); } else { ClientEventListener.get(code).call(ctx.channel(), msg.getData()); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {<FILL_FUNCTION_BODY>} @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if(cause instanceof java.io.IOException) { SimplePrinter.printNotice("The network is not good or did not operate for a long time, has been offline"); System.exit(0); } } }
if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state() == IdleState.WRITER_IDLE) { ChannelUtils.pushToServer(ctx.channel(), ServerEventCode.CODE_CLIENT_HEAD_BEAT, "heartbeat"); } }