Advertisement
Guest User

Untitled

a guest
Apr 19th, 2012
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.53 KB | None | 0 0
  1. package com.larocheent.photomouseserver;
  2.  
  3. import java.awt.EventQueue;
  4.  
  5. import javax.swing.ImageIcon;
  6. import javax.swing.JFrame;
  7. import javax.swing.JOptionPane;
  8. import javax.swing.JPanel;
  9. import javax.swing.JScrollPane;
  10.  
  11. import java.awt.AWTException;
  12. import java.awt.BorderLayout;
  13. import java.awt.Dimension;
  14. import java.awt.Graphics2D;
  15. import java.awt.Robot;
  16. import java.awt.Toolkit;
  17.  
  18. import javax.swing.JButton;
  19. import java.awt.event.InputEvent;
  20. import java.awt.event.KeyEvent;
  21. import java.awt.event.KeyListener;
  22. import java.awt.event.MouseAdapter;
  23. import java.awt.event.MouseEvent;
  24. import java.awt.image.BufferedImage;
  25. import java.io.BufferedReader;
  26. import java.io.IOException;
  27. import java.io.InputStreamReader;
  28. import java.net.InetAddress;
  29. import java.net.ServerSocket;
  30. import java.net.Socket;
  31. import java.net.UnknownHostException;
  32. import java.nio.charset.Charset;
  33. import java.util.Hashtable;
  34.  
  35. import javax.swing.JLabel;
  36. import java.awt.CardLayout;
  37. import java.awt.Component;
  38. import java.awt.Color;
  39. import javax.swing.JTextArea;
  40.  
  41. import com.google.zxing.BarcodeFormat;
  42. import com.google.zxing.EncodeHintType;
  43. import com.google.zxing.WriterException;
  44. import com.google.zxing.common.BitMatrix;
  45. import com.google.zxing.qrcode.QRCodeWriter;
  46. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  47. import java.awt.FlowLayout;
  48. import javax.swing.JTextField;
  49.  
  50. public class ServerStart {
  51.  
  52.     private JFrame frmPhotoMouse;
  53.     private String line;
  54.     private StartServer st;
  55.     private Dimension dim;
  56.    
  57.     private JButton btnSavePort, btnQuit;
  58.    
  59.     final static String SETTINGS_PANEL = "Settings Panel";
  60.     final static String MAIN_PANEL = "Main Panel";
  61.     private JTextArea textArea;
  62.     private JScrollPane sbrText;
  63.     private JLabel qrLabel;
  64.     private JPanel panel;
  65.     private JTextField txtPort;
  66.     private JLabel lblNewLabel;
  67.     private SettingsSaver settingsSaver;
  68.    
  69.     /**
  70.      * Launch the application.
  71.      */
  72.     public static void main(String[] args) {
  73.         EventQueue.invokeLater(new Runnable() {
  74.             public void run() {
  75.                 try {
  76.                     ServerStart window = new ServerStart();
  77.                     window.frmPhotoMouse.setVisible(true);
  78.                 } catch (Exception e) {
  79.                     e.printStackTrace();
  80.                 }
  81.             }
  82.         });
  83.     }
  84.  
  85.     /**
  86.      * Create the application.
  87.      */
  88.     public ServerStart() {
  89.         initialize();
  90.     }
  91.  
  92.     /**
  93.      * Initialize the contents of the frame.
  94.      */
  95.     private void initialize() {
  96.         settingsSaver = new SettingsSaver();
  97.        
  98.         frmPhotoMouse = new JFrame();
  99.         frmPhotoMouse.setResizable(false);
  100.         frmPhotoMouse.setTitle("Photo Mouse");
  101.         frmPhotoMouse.setBounds(100, 100, 338, 306);
  102.         frmPhotoMouse.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  103.        
  104.         JPanel holder_panel = new JPanel();
  105.         frmPhotoMouse.getContentPane().add(holder_panel, BorderLayout.CENTER);
  106.         holder_panel.setLayout(new CardLayout(0, 0));
  107.        
  108.         @SuppressWarnings("unused")
  109.         final CardLayout cardLayout;
  110.         cardLayout = (CardLayout) holder_panel.getLayout();
  111.        
  112.         panel = new JPanel();
  113.         panel.setBackground(Color.WHITE);
  114.         holder_panel.add(panel, MAIN_PANEL);
  115.         panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
  116.                
  117.         JLabel picLabel = new JLabel(new ImageIcon(getClass().getResource("server_logo.png")));
  118.         picLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
  119.         panel.add( picLabel );
  120.        
  121.         qrLabel = new JLabel(new ImageIcon(generateQRCode()));
  122.         qrLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
  123.         panel.add( qrLabel );
  124.        
  125.        
  126.         btnSavePort = new JButton("Save Port");
  127.         btnSavePort.setAlignmentX(Component.CENTER_ALIGNMENT);
  128.         btnSavePort.addMouseListener(new MouseAdapter() {
  129.             @Override
  130.             public void mouseClicked(MouseEvent arg0) {
  131.                 st.interrupt();
  132.                 st = new StartServer(Integer.parseInt(txtPort.getText()));
  133.                 st.start();
  134.                 settingsSaver.savePortNumber(txtPort.getText());
  135.                 qrLabel.setIcon(new ImageIcon(generateQRCode()));
  136.             }
  137.         });
  138.        
  139.         lblNewLabel = new JLabel("Port:");
  140.         panel.add(lblNewLabel);
  141.        
  142.         txtPort = new JTextField();
  143.         SettingsSaver settingsSaver = new SettingsSaver();
  144.         txtPort.setText(settingsSaver.getPortNumber());
  145.         txtPort.addKeyListener(new KeyListener() {
  146.  
  147.             @Override
  148.             public void keyPressed(KeyEvent arg0) {
  149.                
  150.             }
  151.  
  152.             @Override
  153.             public void keyReleased(KeyEvent keyEvent) {
  154.                 if(!Character.isDigit(keyEvent.getKeyChar())) {
  155.                     String input = txtPort.getText();
  156.                     String corrected = input.substring(0, input.length() - 1);
  157.                     txtPort.setText(corrected);
  158.                 }
  159.             }
  160.  
  161.             @Override
  162.             public void keyTyped(KeyEvent keyEvent) {
  163.                
  164.             }
  165.            
  166.         });
  167.         panel.add(txtPort);
  168.         txtPort.setColumns(5);
  169.         panel.add(btnSavePort);
  170.        
  171.         btnQuit = new JButton("Quit");
  172.         btnQuit.setAlignmentX(Component.CENTER_ALIGNMENT);
  173.         btnQuit.addMouseListener(new MouseAdapter() {
  174.             @Override
  175.             public void mouseClicked(MouseEvent arg0) {
  176.                 System.exit(0);
  177.             }
  178.         });
  179.         panel.add(btnQuit);
  180.        
  181.         textArea = new JTextArea("Click the Start Server button above.", 10, 5);
  182.         textArea.setEditable(false);
  183.         textArea.setSize(new Dimension(250, 75));
  184.         textArea.setPreferredSize(new Dimension(100, 70));
  185.         textArea.setMaximumSize(new Dimension(100, 70));
  186.         textArea.setLineWrap(true);
  187.         sbrText = new JScrollPane(textArea);
  188.         sbrText.setPreferredSize(new Dimension(275, 75));
  189.         sbrText.setMaximumSize(new Dimension(275, 75));
  190.         sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
  191.         panel.add(sbrText);
  192.        
  193.         st = new StartServer(Integer.parseInt(settingsSaver.getPortNumber()));
  194.         st.start();
  195.         textArea.setText("Waiting for a connection...\n");
  196.        
  197.         dim = Toolkit.getDefaultToolkit().getScreenSize(); 
  198.     }
  199.    
  200.     private String getNetworkInfo() {
  201.         InetAddress thisIp = null;
  202.         try {
  203.             thisIp = InetAddress.getLocalHost();
  204.         } catch (UnknownHostException e) {
  205.             e.printStackTrace();
  206.         }
  207.         return thisIp.getHostAddress();
  208.     }
  209.    
  210.     private BufferedImage generateQRCode() {
  211.         Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
  212.         hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
  213.        
  214.         QRCodeWriter qrCodeWriter = new QRCodeWriter();
  215.         BitMatrix byteMatrix = null;
  216.         try {
  217.             SettingsSaver settingsSaver = new SettingsSaver();
  218.            
  219.             byteMatrix = qrCodeWriter.encode("IP:" + getNetworkInfo() + ",PORT:" + settingsSaver.getPortNumber(), BarcodeFormat.QR_CODE, 150, 150, hintMap);
  220.         } catch (WriterException e) {
  221.             System.out.println(e);
  222.         }
  223.        
  224.         int matrixWidth = byteMatrix.getWidth();
  225.         BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB);
  226.        
  227.         image.createGraphics();
  228.        
  229.        
  230.        
  231.         Graphics2D graphics = (Graphics2D) image.getGraphics();
  232.         graphics.setColor(Color.WHITE);
  233.         graphics.fillRect(0, 0, matrixWidth, matrixWidth);
  234.        
  235.         graphics.setColor(Color.BLACK);
  236.        
  237.         for (int i = 0; i < matrixWidth; i++) {
  238.             for (int j = 0; j < matrixWidth; j++) {
  239.                 if (byteMatrix.get(i, j)) {
  240.                     graphics.fillRect(i, j, 1, 1);
  241.                 }
  242.             }
  243.         }
  244.        
  245.         return image;
  246.     }
  247.    
  248.     class StartServer extends Thread {
  249.         protected boolean running = true;
  250.         private ServerSocket connection = null;
  251.         private Thread connectionThread = null;
  252.         private int portNumber;
  253.        
  254.         public StartServer(int portNumber) {
  255.             this.portNumber = portNumber;
  256.         }
  257.        
  258.         public void run() {
  259.             try{
  260.                 connection = new ServerSocket(portNumber);
  261.                 connection.setPerformancePreferences(1, 0, 0);
  262.                 textArea.setText("Server started on port: " + portNumber);
  263.             } catch (IOException e) {
  264.                 System.out.println("Could not listen on port " + portNumber);
  265.                 JOptionPane.showMessageDialog(frmPhotoMouse, "This port is already in use. Please choose a different port number!");
  266.             }
  267.              
  268.             while(running){
  269.                 try {
  270.                     connectionThread = new ConnectionThread(connection.accept());
  271.                     connectionThread.start();
  272.                 } catch (IOException e) {
  273.                     System.out.println(e);
  274.                 }
  275.             }
  276.            
  277.             connectionThread.interrupt();
  278.            
  279.             try {
  280.                 connection.close();
  281.             } catch (IOException e) {
  282.                 System.out.println("Could not close ServerSocket");
  283.             }
  284.         }
  285.        
  286.         public void interrupt() {
  287.             this.running = false;
  288.            
  289.             if(connectionThread != null) {
  290.                 connectionThread.interrupt();
  291.             }
  292.  
  293.             Thread.currentThread().interrupt();
  294.             super.interrupt();
  295.         }
  296.     }
  297.    
  298.     class ConnectionThread extends Thread {
  299.         protected Socket clientSocket = null;
  300.        
  301.         protected BufferedReader input = null;
  302.        
  303.         protected boolean running = true;      
  304.  
  305.         private Robot computerController = null;
  306.        
  307.         private double widthScaleFactor, heightScaleFactor;
  308.                
  309.         public ConnectionThread(Socket clientSocket) {
  310.             this.clientSocket = clientSocket;
  311.         }
  312.        
  313.         public void run() {
  314.            
  315.             try {
  316.                 computerController = new Robot();
  317.             } catch (AWTException e1) {
  318.                 System.out.println(e1);
  319.             }
  320.                        
  321.             try {
  322.                input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "US-ASCII"), 2028);
  323.                
  324.                
  325.                while (running == true) {
  326.                    line = input.readLine();
  327.                    handleCommand(line);
  328.                }           
  329.             } catch (IOException e) {
  330.                    System.out.println(e);
  331.             }
  332.         }
  333.        
  334.         public void interrupt() {
  335.             this.running = false;
  336.  
  337.             Thread.currentThread().interrupt();
  338.             super.interrupt();         
  339.         }
  340.        
  341.  
  342.        
  343.         private void handleCommand(String command) {
  344.             String[] splitString = command.split("=");
  345.             String commandType = splitString[0];
  346.  
  347.             if(commandType.contentEquals("Move_Mouse")) {
  348.                 handleMoveMouse(splitString[1]);
  349.             } else if(commandType.contentEquals("Left_Click")) {
  350.                 handleLeftClick();
  351.             } else if(commandType.contentEquals("Right_Click")) {
  352.                 handleRightClick();
  353.             } else if(commandType.contentEquals("Client_Screen_Size")) {
  354.                 handleScreenSize(splitString[1]);
  355.             } else if(commandType.contentEquals("Left_Click_Held")) {
  356.                 handleLeftClickHeld(splitString[1]);
  357.             } else if(commandType.contentEquals("Right_Click_Held")) {
  358.                 handleRightClickHeld(splitString[1]);
  359.             } else if(commandType.contentEquals("Slider_Position")) {
  360.                 handleSliderChange(splitString[1]);
  361.             } else if(commandType.contentEquals("Scale_Up")) {
  362.                 handleScaleUp();
  363.             }
  364.         }
  365.        
  366.         private void handleScaleUp() {
  367.             computerController.keyPress(KeyEvent.VK_ALT);
  368.             computerController.mouseWheel(-1);
  369.             computerController.keyRelease(KeyEvent.VK_ALT);
  370.         }
  371.        
  372.         private void handleSliderChange(String command) {
  373.             if(command.contentEquals("100")) {
  374.                 computerController.keyPress(KeyEvent.VK_0);
  375.                 computerController.keyRelease(KeyEvent.VK_0);
  376.             } else {
  377.                
  378.                 if(command.length() == 1) {
  379.                     controlOpacity(Integer.parseInt(command.substring(0, 1)));
  380.                 } else if(command.length() == 2) {
  381.                     int firstNumber = Integer.parseInt(command.substring(0, 1));
  382.                     int secondNumber = Integer.parseInt(command.substring(1, 2));
  383.                    
  384.                     controlOpacity(firstNumber);
  385.                     controlOpacity(secondNumber);
  386.                 }
  387.                
  388.             }
  389.         }
  390.        
  391.         private void controlOpacity(int level) {
  392.             switch(level) {
  393.             case 0:
  394.                 computerController.keyPress(KeyEvent.VK_0);
  395.                 computerController.keyRelease(KeyEvent.VK_0);
  396.                 break;
  397.             case 1:
  398.                 computerController.keyPress(KeyEvent.VK_1);
  399.                 computerController.keyRelease(KeyEvent.VK_1);
  400.                 break;
  401.             case 2:
  402.                 computerController.keyPress(KeyEvent.VK_2);
  403.                 computerController.keyRelease(KeyEvent.VK_2);
  404.                 break;
  405.             case 3:
  406.                 computerController.keyPress(KeyEvent.VK_3);
  407.                 computerController.keyRelease(KeyEvent.VK_3);
  408.                 break;
  409.             case 4:
  410.                 computerController.keyPress(KeyEvent.VK_4);
  411.                 computerController.keyRelease(KeyEvent.VK_4);
  412.                 break;
  413.             case 5:
  414.                 computerController.keyPress(KeyEvent.VK_5);
  415.                 computerController.keyRelease(KeyEvent.VK_5);
  416.                 break;
  417.             case 6:
  418.                 computerController.keyPress(KeyEvent.VK_6);
  419.                 computerController.keyRelease(KeyEvent.VK_6);
  420.                 break;
  421.             case 7:
  422.                 computerController.keyPress(KeyEvent.VK_7);
  423.                 computerController.keyRelease(KeyEvent.VK_7);
  424.                 break;
  425.             case 8:
  426.                 computerController.keyPress(KeyEvent.VK_8);
  427.                 computerController.keyRelease(KeyEvent.VK_8);
  428.                 break;
  429.             case 9:
  430.                 computerController.keyPress(KeyEvent.VK_9);
  431.                 computerController.keyRelease(KeyEvent.VK_9);
  432.                 break;
  433.             }
  434.         }
  435.        
  436.         private void handleLeftClickHeld(String command) {         
  437.             if(command.contentEquals("true")) {
  438.                 computerController.mousePress(InputEvent.BUTTON1_MASK);
  439.             }
  440.            
  441.             if(command.contentEquals("false")) {
  442.                 computerController.mouseRelease(InputEvent.BUTTON1_MASK);
  443.             }
  444.         }
  445.        
  446.         private void handleRightClickHeld(String command) {        
  447.             if(command.contentEquals("true")) {
  448.                 computerController.mousePress(InputEvent.BUTTON3_MASK);
  449.             }
  450.            
  451.             if(command.contentEquals("false")) {
  452.                 computerController.mouseRelease(InputEvent.BUTTON3_MASK);
  453.             }
  454.         }
  455.        
  456.         private void handleScreenSize(String command) {
  457.             String[] incomingSplit = command.split(",");
  458.             String[] xSplit = incomingSplit[0].split(":");
  459.             String[] ySplit = incomingSplit[1].split(":");
  460.                        
  461.             System.out.println(xSplit[0]);
  462.            
  463.             double padWidth = Double.parseDouble(xSplit[1]);
  464.             double padHeight = Double.parseDouble(ySplit[1]);
  465.            
  466.             double screenWidth = (int)dim.getWidth();
  467.             double screenHeight = (int)dim.getHeight();
  468.            
  469.             widthScaleFactor = screenWidth / padWidth;
  470.             heightScaleFactor = screenHeight / padHeight;
  471.            
  472.             System.out.println("Computer Width: " + screenWidth + ", Computer Height: " + screenHeight);
  473.             System.out.println("Pad Width: " + padWidth + ", Pad Height: " + padHeight);
  474.             System.out.println("Scaled Width: " + widthScaleFactor + ", Scaled Height: " + heightScaleFactor);
  475.         }
  476.        
  477.         private void handleMoveMouse(String command) {
  478.             String[] splitString = command.split(",");         
  479.            
  480.             String[] xPortion = splitString[0].split(":");
  481.             String[] yPortion = splitString[1].split(":");
  482.                        
  483.             int xCord = Integer.parseInt(xPortion[1]);
  484.             int yCord = Integer.parseInt(yPortion[1]);
  485.            
  486.             double x = xCord * widthScaleFactor;
  487.             double y = yCord * heightScaleFactor;
  488.            
  489.             computerController.mouseMove((int) x, (int) y);    
  490.         }
  491.        
  492.         private void handleLeftClick() {
  493.             computerController.mousePress(InputEvent.BUTTON1_MASK);
  494.             computerController.mouseRelease(InputEvent.BUTTON1_MASK);
  495.         }
  496.        
  497.         private void handleRightClick() {
  498.             computerController.mousePress(InputEvent.BUTTON3_MASK);
  499.             computerController.mouseRelease(InputEvent.BUTTON3_MASK);
  500.         }
  501.        
  502.        
  503.     }
  504. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement