Package ui

Source Code of ui.WCViewer

package ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Scanner;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;

import ui.WCVPreferences.ViewerMode;
import webcam.WCVCam;

@SuppressWarnings("serial")
public class WCViewer extends JFrame {

  private static final String CAMLIST_FILE =  System.getProperty("user.home") +
      "/.config/wcviewer/camlist";
  private static final String CONFIG_FILE =  System.getProperty("user.home") +
      "/.config/wcviewer/config";
  public static final String ICON_32x32 = "icons/32x32/wcviewer-icon.png";
  public static final String ICON_64x64 = "icons/64x64/wcviewer-icon.png";
  public static final String ICON_128x128 = "icons/128x128/wcviewer-icon.png";
  public static final String ICON_256x256 = "icons/256x256/wcviewer-icon.png";
  public static final int REFRESH_TIME = 1000*180; //Milliseconds; 3 minutes
  public static final int WIDTH = 320;
  public static final int HEIGHT = 235;

  private static final int BUTTON_HEIGHT = 16;
  private static final int BUTTON_WIDTH = 80;
  private static final Font menuFont = new Font("Sans Serif", Font.PLAIN, 14);
  private static final Font itemFont = new Font("Sans Serif", Font.PLAIN, 11);
  private final Timer timer;
  private int camNum;
  private WCVCamPanel webcamPanel;
  private WCVZoomView webcamWindow;
  private final JMenuBar menuBar;
  private JMenu webcamMenu, fileMenu;
  private JMenuItem rmItem, addItem;
  private JButton btnRecord, btnRefresh;
  private boolean record, emptyCamList, inMinMode, lowerInMin;
  private ArrayList<WCVCam> cams;

  public WCViewer() {
    super("Webcam Viewer");
    //Frame
    setResizable(false);
    setName("Webcam Viewer");
    List<Image> icons = new ArrayList<Image>();
    icons.add(new ImageIcon(this.getClass().getClassLoader().getResource(ICON_32x32)).getImage());
    icons.add(new ImageIcon(this.getClass().getClassLoader().getResource(ICON_64x64)).getImage());
    icons.add(new ImageIcon(this.getClass().getClassLoader().getResource(ICON_128x128)).getImage());
    icons.add(new ImageIcon(this.getClass().getClassLoader().getResource(ICON_256x256)).getImage());
    setIconImages(icons);
    setPreferredSize(new Dimension(WIDTH, HEIGHT));
    getContentPane().setLayout(null);
    //Position at top left of display
    setBounds((int) Toolkit.getDefaultToolkit().getScreenSize().getWidth()-WIDTH,
        0, WIDTH, HEIGHT);
    this.record = false; emptyCamList = true; this.inMinMode = false;
    this.lowerInMin = false;
    this.camNum = 0;
    //Menu Bar
    this.menuBar = new JMenuBar();
    loadMenu();
    setJMenuBar(menuBar);
    //Image Pane
    this.webcamPanel = new WCVCamPanel();
    setVisible(true);
    Dimension panelDim = getContentPane().getSize();
    loadImagePane(panelDim);
    getContentPane().add(webcamPanel);
    if(!emptyCamList) {
      webcamMenu.getItem(camNum).setBackground(Color.YELLOW);
      webcamPanel.setCam(cams.get(camNum));
    }
    //Buttons
    loadGUIBtns();
    //Centre Window
    this.webcamWindow = null;
    //Timer
    this.timer = new Timer(REFRESH_TIME, new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        refreshTimerActionPerformed();
      }
    });
    timer.start();
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent we) {
        exitItemActionPerformed();
      }
    });
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    pack();
    startup(false);
    webcamPanel.paintLoadingScreen();
    //Wait 5 seconds for network connection establishment
    int i = 0;
    while(!isInternetReachable() && i < 7) {
      try {
        System.out.println("Waiting for network connection...");
        Thread.sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      i++;
    }
    refreshTimerActionPerformed();
  }


  /**********************************************************
   * Initialisation Functions                               *
   **********************************************************/

  /**
   * Checks for connection to the internet through dummy
   * request.
   */
  public static boolean isInternetReachable() {
    try {
      //Make a URL to a reliable source
      URL url = new URL("http://www.google.com");

      //Open a connection to that source
      HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();

      //Trying to retrieve data from the source. If there
      //is no connection, this line will fail
      Object objData = urlConnect.getContent();
    }
    catch (UnknownHostException e) {
      return false;
    }
    catch (IOException e) {
      return false;
    }
    return true;
  }


  private void startup(boolean missingConfig) {
    //Show Welcome dialog
    if(missingConfig) {
      //Write default configuration file
      writeDefaultConfigFile();
      if(JOptionPane.showConfirmDialog(this,"Please Choose A Folder To Store Webcam Images",
          "Welcome", JOptionPane.OK_CANCEL_OPTION) == 0) {
        //User specify the image directory, else default home
        WCVPreferences.imgDirDialog();
        setSavedImgDir(WCVPreferences.getSavedImgDir(), true);
      }
      //Now start as normal
      startup(false);
    }
    //Start in regular user mode
    else {
      btnRecord.setEnabled(true);
      rmItem.setEnabled(true);
      try {
        String dir = ""; int min = 0; ViewerMode view = ViewerMode.CENTRE;
        boolean start = true; boolean top = false;
        //Read the Webcam Viewer configuration file
        Scanner scan = new Scanner(new File(CONFIG_FILE));
        while(scan.hasNextLine()) {
          ConfigOptions option = ConfigOptions.fromCfgText(scan.nextLine());
          switch(option) {
          case IMGDIR:
            dir = scan.nextLine();
            setSavedImgDir(dir, false);
            break;
          case MINLOWER:
            if(scan.nextLine().equalsIgnoreCase("TRUE")) {
              min = 1;
              setMinMode(min, false);
            }
            else {
              min = 0;
              setMinMode(min, false);
            }
            break;
          case VIEWER:
            view = ViewerMode.valueOf(scan.nextLine());
            setViewerMode(view , false);
            break;
          case STARTUP:
            if(scan.nextLine().equalsIgnoreCase("TRUE")) {
              start = true;
            }
            else {
              start = false;
            }
            break;
          case ALWAYSTOP:
            if(scan.nextLine().equalsIgnoreCase("TRUE")) {
              top = true;
              setOnTopMode(top, false);
            }
            else {
              top = false;
              setOnTopMode(top, false);
            }
            break;
          default:
            break;
          }
        }
        WCVPreferences.loadSavedPrefs(dir, min, view, start, top);

        if(start) minimalKeyActionPerformed();
      }
      catch (FileNotFoundException e) {
        //Missing config file, run the welcome dialog, and create new config file
        startup(true);
      }
      catch(IllegalArgumentException e) {
        //Corrupt config file, run the welcome dialog, and create new config file
        startup(true);
      }
    }
  }

  private void loadMenu() {
    webcamMenu = new JMenu();
    webcamMenu.setText("Webcam");
    webcamMenu.setFont(menuFont);
    cams = new ArrayList<WCVCam>();
    menuBar.removeAll();
    emptyCamList = true;

    //File Menu
    fileMenu = new JMenu();
    fileMenu.setText("File");
    fileMenu.setFont(menuFont);
    loadFileMenu(fileMenu);
    menuBar.add(fileMenu);

    //Cam Menu
    try{
      WCVCam cam;
      File camsList = new File(CAMLIST_FILE);
      camsList.getParentFile().mkdirs();
      camsList.createNewFile();
      Scanner scan = new Scanner(camsList);
      int i = 0; String camURL;
      JMenuItem item;
      while(scan.hasNextLine()) {
        item = new JMenuItem();
        item.setOpaque(true);
        String camTitle[] = scan.nextLine().split(", ");
        if(camTitle[0].contains("****")) {
          //"****" Marks the most recently viewed cam
          camTitle[0] = camTitle[0].substring(5);
          camNum = i;
        }
        camURL = scan.nextLine();
        if(camTitle.length == 1 || camTitle[1] == "") {
          cam = new WCVCam(camTitle[0], "", camURL);
          cam.setImageViewerMode(WCVPreferences.getViewerMode());
          cams.add(cam);
          item.setText(camTitle[0]);
        }
        else {
          cam = new WCVCam(camTitle[0], camTitle[1], camURL);
          cam.setImageViewerMode(WCVPreferences.getViewerMode());
          cams.add(cam);
          item.setText(camTitle[0] + ", " + camTitle[1]);
        }
        item.setFont(itemFont);
        item.addActionListener(new CamSwitchListener(i));
        webcamMenu.add(item);
        i++;
      }
      if(i != 0) {
        emptyCamList = false;
      }
    }
    catch(IOException e) {
      System.out.println("WebcamViewer file inaccessable in " + CAMLIST_FILE);
    }

    //Add Cam Item
    addItem = new JMenuItem();
    addItem.setText("Add New...");
    addItem.setFont(new Font("Sans Serif", Font.BOLD, 11));
    addItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        addCamItemActionPerformed(evt);
      }
    });

    //Remove Cam Item
    rmItem = new JMenuItem();
    rmItem.setText("Remove Cam...");
    rmItem.setFont(new Font("Sans Serif", Font.BOLD, 11));
    if(emptyCamList) rmItem.setEnabled(false);
    rmItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        rmCamItemActionPerformed(evt);
      }
    });
    webcamMenu.add(addItem);
    webcamMenu.add(rmItem);
    menuBar.add(webcamMenu);
  }

  private void loadFileMenu(JComponent menu) {
    menu.removeAll();
    //Refresh Menubar Item
    JMenuItem refreshItem = new JMenuItem();
    refreshItem.setText("Refresh");
    refreshItem.setFont(itemFont);
    refreshItem.setMnemonic(KeyEvent.VK_R);
    refreshItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        refreshTimerActionPerformed();
      }
    });

    //Record Menubar Item
    JMenuItem recordItem = new JMenuItem();
    recordItem.setText("Record");
    recordItem.setFont(itemFont);
    recordItem.setOpaque(true);
    if(record) recordItem.setBackground(Color.YELLOW);
    recordItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        recordActionPerformed();
      }
    });

    //Minimal View Menubar Item
    JMenuItem minimalItem = new JMenuItem();
    minimalItem.setText("Minimal");
    minimalItem.setFont(itemFont);
    minimalItem.setOpaque(true);
    minimalItem.setMnemonic(KeyEvent.VK_M);
    if(inMinMode) minimalItem.setBackground(Color.YELLOW);
    minimalItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        minimalKeyActionPerformed();
      }
    });

    //Centre Window Menubar Item
    JMenuItem cWinItem = new JMenuItem();
    cWinItem.setText("Zoom View");
    cWinItem.setFont(itemFont);
    cWinItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        centreWindowActionPerformed();
      }
    });

    //Preferences Menubar Item
    JMenuItem prefItem = new JMenuItem();
    prefItem.setText("Preferences");
    prefItem.setFont(itemFont);
    prefItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        preferencesActionPerformed();
      }
    });

    //Exit app. Item
    JMenuItem exitItem = new JMenuItem();
    exitItem.setText("Exit");
    exitItem.setFont(new Font("Sans Serif", Font.BOLD, 11));
    exitItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        exitItemActionPerformed();
      }
    });

    menu.add(refreshItem);
    menu.add(recordItem);
    menu.add(minimalItem);
    menu.add(cWinItem);
    menu.add(prefItem);
    menu.add(exitItem);
  }

  private void loadImagePane(Dimension size) {
    webcamPanel.setFocusable(true);
    webcamPanel.setLayout(null);
    webcamPanel.setSize(size);
    webcamPanel.getInputMap().put(
        KeyStroke.getKeyStroke(KeyEvent.VK_M,
            0, true)"minimal");
    webcamPanel.getActionMap().put("minimal",
        new AbstractAction("minimal") {
      public void actionPerformed(ActionEvent evt) {
        minimalKeyActionPerformed();
      }
    });
    webcamPanel.getInputMap().put(
        KeyStroke.getKeyStroke(KeyEvent.VK_R,
            0, true)"refresh");
    webcamPanel.getActionMap().put("refresh",
        new AbstractAction("refresh") {
      public void actionPerformed(ActionEvent evt) {
        refreshTimerActionPerformed();
      }
    });
    webcamPanel.getInputMap().put(
        KeyStroke.getKeyStroke(KeyEvent.VK_K,
            0, true), "nextcam");
    webcamPanel.getActionMap().put("nextcam",
        new AbstractAction("nextcam") {
      public void actionPerformed(ActionEvent evt) {
        cycleCamKeyActionPerformed(1);
      }
    });
    webcamPanel.getInputMap().put(
        KeyStroke.getKeyStroke(KeyEvent.VK_J,
            0, true), "prevcam");
    webcamPanel.getActionMap().put("prevcam",
        new AbstractAction("prevcam") {
      public void actionPerformed(ActionEvent evt) {
        cycleCamKeyActionPerformed(-1);
      }
    });
    webcamPanel.addMouseWheelListener(new ScrollListener());
    webcamPanel.addMouseListener(new DClickListener());
    webcamPanel.addMouseListener(new PopClickListener());

  }

  private void loadGUIBtns() {
    Font btnFont = new Font("Sans Serif", Font.PLAIN, 11);
    this.btnRefresh = new JButton("Refresh");
    btnRefresh.setFont(btnFont);
    btnRefresh.setBounds(4, webcamPanel.getHeight()-BUTTON_HEIGHT-4,
        BUTTON_WIDTH, BUTTON_HEIGHT);
    btnRefresh.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        refreshTimerActionPerformed();
      }
    });
    this.btnRecord = new JButton("Record");
    btnRecord.setFont(btnFont);
    btnRecord.setEnabled(false);
    btnRecord.setBounds(webcamPanel.getWidth()-BUTTON_WIDTH-4,
        webcamPanel.getHeight()-BUTTON_HEIGHT-4,
        BUTTON_WIDTH, BUTTON_HEIGHT);
    btnRecord.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent evt) {
        recordActionPerformed();
      }
    });
    webcamPanel.add(btnRefresh);
    webcamPanel.add(btnRecord);
    webcamPanel.validate();
  }

  /**********************************************************
   * Call-back Functions                                    *
   **********************************************************/

  /**
   * Refresh the display automatically after a fixed time
   * period.
   *
   * @param evt
   */
  public void refreshTimerActionPerformed() {
    webcamPanel.refreshDisplay();
    webcamPanel.requestFocusInWindow();
  }

  public void recordActionPerformed() {
    if(!record) {
      record = true;
      cams.get(camNum).setRecordCam(record);
      btnRecord.setText("Recording...");
    }
    else {
      record = false;
      cams.get(camNum).setRecordCam(record);
      btnRecord.setText("Record");
    }
    loadFileMenu(fileMenu);
    webcamPanel.requestFocusInWindow();
  }

  public void exitItemActionPerformed() {
    if(!record && cams.size() > 0 ) {
      cams.get(camNum).deletePrevImg();
    }
    writeCamListFile();
    System.exit(0);
  }

  private void preferencesActionPerformed() {
    timer.stop();
    new WCVPreferences(this);
  }

  private void minimalKeyActionPerformed() {

    int currWidth = getPreferredSize().width;
    int currHeight = getPreferredSize().height;

    if(isUndecorated()) {
      //hide the frame so we can change it.
      setVisible(false);
      dispose();
      setUndecorated(false);
      inMinMode = false;
      setPreferredSize(new Dimension(WIDTH, HEIGHT));
      setSize(new Dimension(WIDTH, HEIGHT));
      setJMenuBar(menuBar);
      btnRecord.setVisible(true); btnRefresh.setVisible(true);
      webcamPanel.setBorder(false);
    }
    else {
      //hide the frame so we can change it.
      setVisible(false);
      dispose();
      setUndecorated(true);
      inMinMode = true;
      webcamPanel.setBorder(true);
      setPreferredSize(new Dimension(webcamPanel.getWidth(),
          webcamPanel.getHeight()));
      setJMenuBar(null);
      btnRecord.setVisible(false); btnRefresh.setVisible(false);
    }
    if(lowerInMin) {
      //Lower in Minimal mode
      setLocation(getLocation().x+currWidth-getPreferredSize().width,
          getLocation().y+currHeight-getPreferredSize().height);
    }
    else {
      //Raise
      setLocation(getLocation().x+currWidth-getPreferredSize().width,
          getLocation().y);
    }
    setVisible(true);
    pack();
    loadFileMenu(fileMenu);
    webcamPanel.requestFocusInWindow();
  }

  private void cycleCamKeyActionPerformed(int cycle) {
    int camMenuNum;
    if(camNum+cycle < 0) {
      camMenuNum = cams.size()-1;
    }
    else if(camNum+cycle == cams.size()) {
      camMenuNum = 0;
    }
    else camMenuNum = camNum+cycle;

    switchCam(camMenuNum);
  }

  public void addCamItemActionPerformed(ActionEvent evt) {
    String inURL = (String)JOptionPane.showInputDialog(
        this,
        "Enter a Webcam URL",
        "Add New Webcam",
        JOptionPane.PLAIN_MESSAGE);

    if (inURL == null || inURL.length() == 0) {
      JOptionPane.showMessageDialog(this,
          "Webcam URL is not Valid",
          "Error", JOptionPane.ERROR_MESSAGE);
    }
    else {
      String inName = (String)JOptionPane.showInputDialog(
          this,
          "Enter a Name for this Webcam",
          "Add New Webcam",
          JOptionPane.PLAIN_MESSAGE);

      if (inName == null || inName.length() == 0) {
        JOptionPane.showMessageDialog(this,
            "Enter a Valid Webcam Name/Location",
            "Error", JOptionPane.ERROR_MESSAGE);
      }
      else {
        String inLoc = (String)JOptionPane.showInputDialog(
            this,
            "Enter a Country or Region for this Webcam",
            "Add New Webcam",
            JOptionPane.PLAIN_MESSAGE);
        WCVCam cam = new WCVCam(inName, inLoc, inURL);
        cams.add(cam);
        writeCamListFile();
        //Note writeCamList sorts the cams by region
        int camInd = cams.indexOf(cam);
        loadMenu();
        if(!emptyCamList) {
          btnRecord.setEnabled(true);
          rmItem.setEnabled(true);
        }
        switchCam(camInd);
        setJMenuBar(menuBar);
        pack();
      }
    }
  }

  public void rmCamItemActionPerformed(ActionEvent evt) {
    if(JOptionPane.showConfirmDialog(this,
        "Delete the Current Webcam?",
        "Delete Webcam", JOptionPane.YES_NO_OPTION) == 0 && cams.size() >= 1) {
      cams.remove(camNum);
      System.out.println("Deleting Current Webcam");
      writeCamListFile();
      loadMenu();
      setJMenuBar(menuBar);
      if(emptyCamList) {
        btnRecord.setEnabled(false);
        rmItem.setEnabled(false);
        webcamPanel = new WCVCamPanel();
        refreshTimerActionPerformed();
      }
      else cycleCamKeyActionPerformed(-1);
      pack();
    }
  }

  public void centreWindowActionPerformed() {
    if(webcamWindow == null || !webcamWindow.isVisible()) {
      this.setVisible(false);
      webcamWindow = new WCVZoomView(webcamPanel.getCam());
      webcamWindow.addMouseListener(new DClickListener());
      webcamWindow.addKeyListener(new KeyListener(){
        public void keyPressed(KeyEvent ev) {
          if(ev.getKeyCode() == KeyEvent.VK_ESCAPE) {
            hideCentreWindow();
          }
        }
        public void keyReleased(KeyEvent e) {}
        public void keyTyped(KeyEvent e) {}
      });
    }
    else {
      hideCentreWindow();
    }
  }

  private void hideCentreWindow() {
    System.out.println("Dispose Centre Window");
    this.setVisible(true);
    webcamWindow.setVisible(false);
    webcamWindow.dispose();
  }

  /**********************************************************
   * Internal Functions                                    *
   **********************************************************/

  private void switchCam(int newCam) {
    webcamPanel.setCam(cams.get(newCam));
    webcamMenu.getItem(camNum).setBackground(null);
    webcamMenu.getItem(newCam).setBackground(Color.YELLOW);
    camNum = newCam;
    refreshTimerActionPerformed();
  }

  private static void fixWmClass() {
    try {
      Toolkit xToolkit = Toolkit.getDefaultToolkit();
      java.lang.reflect.Field awtAppClassNameField =
          xToolkit.getClass().getDeclaredField("awtAppClassName");
      awtAppClassNameField.setAccessible(true);
      awtAppClassNameField.set(xToolkit, "wcviewer");
    }
    catch (Throwable th) {
      th.printStackTrace();
    }
  }

  private boolean writeCamListFile() {
    File config = new File(CAMLIST_FILE);
    config.getParentFile().mkdirs();
    Collections.sort(cams);
    try {
      config.createNewFile();
      FileWriter out = new FileWriter(config, false);
      for(int i = 0; i < cams.size(); i++) {
        if(i == camNum) {
          //Mark this as the current cam
          out.write("**** ");
        }
        out.write(cams.get(i).getCamName() + ", " +
            cams.get(i).getCamLocation() + "\n" +
            cams.get(i).getCamURL() + "\n");
      }
      out.close();
      return true;
    }
    catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }

  private boolean writeDefaultConfigFile() {
    File config = new File(CONFIG_FILE);
    config.getParentFile().mkdirs();
    try {
      config.createNewFile();
      FileWriter out = new FileWriter(config, false);
      out.write(ConfigOptions.IMGDIR.getCfgText() + "\n");
      out.write(System.getProperty("user.home") + "\n");
      out.write(ConfigOptions.MINLOWER.getCfgText() + "\n");
      out.write("FALSE" + "\n");
      out.write(ConfigOptions.VIEWER.getCfgText() + "\n");
      out.write("CENTRE" + "\n");
      out.write(ConfigOptions.STARTUP.getCfgText() + "\n");
      out.write("TRUE" + "\n");
      out.write(ConfigOptions.ALWAYSTOP.getCfgText() + "\n");
      out.write("FALSE" + "\n");
      out.close();
      return true;
    }
    catch (IOException e) {
      e.printStackTrace();
      return false;
    }
  }

  private boolean writeConfigFile(ConfigOptions cfgOpt, String cfgLine) {
    File config = new File(CONFIG_FILE);
    config.getParentFile().mkdirs();
    try {
      config.createNewFile();
      Scanner scan = new Scanner(config);
      String configStr = "";
      for (ConfigOptions opt: ConfigOptions.values()) {
        String line = scan.nextLine();
        configStr = configStr.concat(line + "\n");
        //If NOT the line we want to update...
        if(line.compareToIgnoreCase(cfgOpt.getCfgText()) != 0) {
          configStr = configStr.concat(scan.nextLine() + "\n");
        }
        else {
          configStr = configStr.concat(cfgLine + "\n");
          scan.nextLine();
        }
      }
      FileWriter out = new FileWriter(config, false);
      out.write(configStr);
      out.close();
    }
    catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    catch(NoSuchElementException e) {
      System.out.println("Malformed config File, Exiting");
      config.delete();
    }
    return true;
  }

  /**********************************************************
   * Setter/Getter Functions                                    *
   **********************************************************/

  public void restartRefreshTimer() {
    timer.start();
  }

  public boolean setStartupMode(boolean startMin, boolean write) {
    if(write) {
      if(startMin) {
        return writeConfigFile(ConfigOptions.STARTUP, "TRUE");
      }
      else {
        return writeConfigFile(ConfigOptions.STARTUP, "FALSE");
      }
    }
    else return true;
  }

  public boolean setOnTopMode(boolean aOnTop, boolean write) {
    setAlwaysOnTop(aOnTop);
    if(write) {
      if(aOnTop) {
        return writeConfigFile(ConfigOptions.ALWAYSTOP, "TRUE");
      }
      else {
        return writeConfigFile(ConfigOptions.ALWAYSTOP, "FALSE");
      }
    }
    else return true;
  }

  public boolean setMinMode(int code, boolean write) {
    //Write to config file
    if(code == 0) lowerInMin = false;
    else if(code == 1) lowerInMin = true;

    if(write) {
      if(lowerInMin) {
        return writeConfigFile(ConfigOptions.MINLOWER, "TRUE");
      }
      else {
        return writeConfigFile(ConfigOptions.MINLOWER, "FALSE");
      }
    }
    return true;
  }

  public boolean setViewerMode(ViewerMode mode, boolean write) {
    for(WCVCam cam: cams) {
      cam.setImageViewerMode(mode);
    }
    if(write) {
      return writeConfigFile(ConfigOptions.VIEWER, mode.toString());
    }
    return true;
  }

  public boolean setSavedImgDir(String imgDir, boolean write) {
    WCVCam.setPhotoDir(imgDir);
    if(write) {
      File newDir = new File(imgDir);
      if(!newDir.isDirectory()) newDir.mkdir();
      if(writeConfigFile(ConfigOptions.IMGDIR, imgDir)) return true;
      else return false;
    }
    else return true;
  }

  /**********************************************************
   * Listener Internal Classes                                   *
   **********************************************************/

  private class CamSwitchListener implements ActionListener {
    int camMenuNum;
    public CamSwitchListener(int cam) {
      camMenuNum = cam;
    }
    public void actionPerformed(ActionEvent e) {
      switchCam(camMenuNum);
    }
  }

  private class ScrollListener implements MouseWheelListener {

    public ScrollListener() {
      super();
    }

    public void mouseWheelMoved(MouseWheelEvent ev) {
      if(!emptyCamList) {
        cycleCamKeyActionPerformed(ev.getWheelRotation());
      }
    }
  }

  private class PopupFileMenu extends JPopupMenu {
    public PopupFileMenu(){
      loadFileMenu(this);
    }
  }

  private class PopClickListener extends MouseAdapter {
    public void mousePressed(MouseEvent e){
      if (e.isPopupTrigger())
        doPop(e);
    }

    public void mouseReleased(MouseEvent e){
      if (e.isPopupTrigger())
        doPop(e);
    }

    private void doPop(MouseEvent e){
      PopupFileMenu popMenu = new PopupFileMenu();
      popMenu.show(e.getComponent(), e.getX(), e.getY());
    }
  }

  private class DClickListener implements MouseListener {
    public DClickListener() {
      super();
    }
    public void mouseClicked(MouseEvent ev) {
      if(ev.getClickCount() == 2) {
        centreWindowActionPerformed();
      }
    }
    public void mouseEntered(MouseEvent ev) {}
    public void mouseExited(MouseEvent ev) {}
    public void mousePressed(MouseEvent ev) {}
    public void mouseReleased(MouseEvent ev) {}
  }

  public enum ConfigOptions {
    IMGDIR("Save Image Directory: <DIRPATH>"),
    MINLOWER("Lower Frame In Minimal Mode: <TRUE/FALSE>"),
    VIEWER("Image Viewer Mode: <CENTRE/SCALEH/SCALEW>"),
    STARTUP("Startup In Minimal Mode: <TRUE/FALSE>"),
    ALWAYSTOP("Always Keep Webcam Viewer On Top: <TRUE/FALSE>");

    String configFileText;

    private ConfigOptions(String text) {
      this.configFileText = text;
    }

    public String getCfgText() {
      return configFileText;
    }

    public static ConfigOptions fromCfgText(String text) {
      for (ConfigOptions b : ConfigOptions.values()) {
        if (text.compareToIgnoreCase(b.configFileText) == 0) {
          return b;
        }
      }
      throw new IllegalArgumentException("No Config Option " + text + " Found");
    }
  }

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
      //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        fixWmClass();
        new WCViewer();
      }
    });
  }
}
TOP

Related Classes of ui.WCViewer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.