package main;
import business.CenarioVolume;
import business.Projeto;
import dao.ProjetoDAO;
import java.awt.AWTKeyStroke;
import java.io.IOException;
import view.helpers.IconNodeRenderer;
import view.helpers.IconNode;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyVetoException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.logging.Level;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import main.states.AbstractMainState;
import main.states.ProjetoFechado;
import org.jdesktop.swingx.JXErrorPane;
import org.jdesktop.swingx.JXStatusBar;
import org.jdesktop.swingx.JXTree;
import org.jdesktop.swingx.error.ErrorInfo;
import org.mdidesktoppane.MDIDeskTopPane;
import org.pushingpixels.flamingo.api.common.JCommandButton;
import org.pushingpixels.flamingo.api.common.RichTooltip;
import org.pushingpixels.flamingo.api.common.icon.ImageWrapperResizableIcon;
import org.pushingpixels.flamingo.api.common.icon.ResizableIcon;
import org.pushingpixels.flamingo.api.ribbon.JRibbonBand;
import org.pushingpixels.flamingo.api.ribbon.JRibbonFrame;
import org.pushingpixels.flamingo.api.ribbon.RibbonElementPriority;
import org.pushingpixels.flamingo.api.ribbon.RibbonTask;
import org.pushingpixels.flamingo.api.ribbon.resize.CoreRibbonResizePolicies;
import org.pushingpixels.flamingo.api.ribbon.resize.IconRibbonBandResizePolicy;
import presenter.AbreProjetoPresenter;
import presenter.CenarioVolumePresenter;
import presenter.DuplicarCenarioPresenter;
import presenter.ModelosPresenter;
import presenter.ProjetoPresenter;
import view.CenarioVolumeView;
import view.ConfiguracoesView;
import view.SplashView;
import presenter.strategy.cenario.EdicaoCenario;
import presenter.strategy.cenario.InclusaoCenario;
import presenter.strategy.projeto.EdicaoProjeto;
import presenter.strategy.projeto.InclusaoProjeto;
public final class Main extends JRibbonFrame {
private JXStatusBar stbMain;
private MDIDeskTopPane desktop;
private JScrollPane scrNavigator;
private JSplitPane splMain;
private JXTree treeNavigator;
int iVolume = 0;
int iLocal = 0;
private ProjetoDAO projetoDAO;
private business.Projeto projeto;
private JCommandButton btnVolumeNovoCenario;
private JCommandButton btnVolumeDuplicarCenario;
private JCommandButton btnIndLocalNovoCenario;
private JCommandButton btnFecharProjeto;
private JCommandButton btnAbrirProjeto;
private JCommandButton btnNovoProjeto;
private AbstractMainState state;
private JPopupMenu menuTree;
private IconNode noSelecionado;
public Main() {
this.setVisible(false);
projetoDAO = new ProjetoDAO();
initComponents();
}
public static void main(String args[]) {
try {
Configuracao.getInstance();
} catch (Exception ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(null, info);
}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Main().setVisible(false);
}
});
}
private void createTree() {
treeNavigator.setCellRenderer(new IconNodeRenderer());
state.updateTreeModel();
menuTree = new JPopupMenu();
JMenuItem miExcluir = new JMenuItem("Excluir projeto", new ImageIcon(Configuracao.getPath() + "images/delete.png"));
miExcluir.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int option = JOptionPane.showOptionDialog(
null,
"Deseja realmente excluir o projeto " + projeto.getNome() + " ?",
"Exclusão permanente", JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE, null, null,
null);
if (option == JOptionPane.YES_OPTION) {
state.fecharProjeto();
projetoDAO.connect();
projetoDAO.delete(projetoDAO.find(projeto.getId()));
projetoDAO.close();
}
} catch (Exception ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(null, info);
}
}
});
menuTree.setInvoker(treeNavigator);
menuTree.add(miExcluir);
treeNavigator.remove(menuTree);
treeNavigator.add(menuTree);
treeNavigator.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
if (e.getClickCount() == 1) {
switch (e.getButton()) {
case MouseEvent.BUTTON1: {
if (treeNavigator.getLastSelectedPathComponent() != null) {
String noSelecionado = ((IconNode) treeNavigator.getLastSelectedPathComponent()).toString();
IconNode no = ((IconNode) treeNavigator.getLastSelectedPathComponent());
if (noSelecionado.equals("Projeto")) {
ProjetoPresenter projetoPresenter = new ProjetoPresenter(Main.this);
projetoPresenter.setStrategy(new EdicaoProjeto(projeto.getId(), projetoPresenter.getView()));
activePanel(projetoPresenter.getView());
} else if ((((ImageIcon) no.getIcon()).getDescription().contains("cenario2.png"))) {
CenarioVolume cenario = projeto.getCenarioById(no.getId());
CenarioVolumePresenter presenterEditaCenario = new CenarioVolumePresenter(Main.this);
removeFrameVolume();
presenterEditaCenario.setStrategy(new EdicaoCenario(projeto.getId(), cenario.getId(), presenterEditaCenario.getView()));
activePanel(presenterEditaCenario.getView());
} else {
desktop.removeAll();
desktop.updateUI();
}
treeNavigator.updateUI();
treeNavigator.expandPath(treeNavigator.getLeadSelectionPath());
break;
}
}
default: {
if (e.isPopupTrigger() && projeto != null) {
noSelecionado = ((IconNode) treeNavigator.getLastSelectedPathComponent());
JMenuItem miExcluirCenario = new JMenuItem("Excluir cenário", new ImageIcon(Configuracao.getPath() + "images/deleteCenario.png"));
miExcluirCenario.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
projetoDAO.connect();
projeto.removeCenario(noSelecionado.toString());
removeFrameVolume();
projetoDAO.update(projeto, false, projeto.getId());
state.updateTreeModel();
projetoDAO.close();
} catch (Exception ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(null, info);
}
}
});
if (treeNavigator.getLastSelectedPathComponent() != null) {
if (((ImageIcon) noSelecionado.getIcon()).getDescription().contains("cenario2.png")) {
if (!containsMenuItem(miExcluirCenario.getText())) {
menuTree.add(miExcluirCenario);
}
} else {
removeMenuItem(miExcluirCenario.getText());
}
}
menuTree.show((Component) e.getSource(), e.getX(), e.getY());
}
break;
}
}
}
}
});
}
private void activePanel(JInternalFrame frame) {
try {
if (!desktop.contain(frame)) {
desktop.remove(frame);
desktop.add(frame);
// Colocando enter para pular de campo
HashSet conj = new HashSet(frame.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
conj.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_ENTER, 0));
frame.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, conj);
frame.setVisible(true);
frame.setMaximizable(true);
frame.setMaximum(true);
}
} catch (PropertyVetoException ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(Main.this, info);
}
}
private void createToolbar() {
JRibbonBand projetoBand = new JRibbonBand("Projeto", getResizableIconFromResource("exit.png"));
projetoBand.setResizePolicies((List) Arrays.asList(
new CoreRibbonResizePolicies.None(projetoBand.getControlPanel()),
new CoreRibbonResizePolicies.None(projetoBand.getControlPanel()),
new CoreRibbonResizePolicies.None(projetoBand.getControlPanel()),
new IconRibbonBandResizePolicy(projetoBand.getControlPanel())));
btnNovoProjeto = new JCommandButton(null, getResizableIconFromResource("new.png"));
btnNovoProjeto.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
novoProjeto();
}
});
btnAbrirProjeto = new JCommandButton(null, getResizableIconFromResource("open.png"));
btnAbrirProjeto.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
AbreProjetoPresenter abreProjeto = new AbreProjetoPresenter();
if (abreProjeto.getProjeto() != null) {
abreProjeto(abreProjeto.getProjeto());
}
}
});
btnFecharProjeto = new JCommandButton(null, getResizableIconFromResource("close.png"));
btnFecharProjeto.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
projeto = null;
state.fecharProjeto();
}
});
JCommandButton btnArvores = new JCommandButton(null, getResizableIconFromResource("arvores.png"));
projetoBand.addCommandButton(btnNovoProjeto, RibbonElementPriority.TOP);
projetoBand.addCommandButton(btnAbrirProjeto, RibbonElementPriority.TOP);
projetoBand.addCommandButton(btnFecharProjeto, RibbonElementPriority.TOP);
projetoBand.addCommandButton(btnArvores, RibbonElementPriority.TOP);
// Volume Band
JRibbonBand volumeBand = new JRibbonBand("Volume", getResizableIconFromResource("exit.png"));
volumeBand.setResizePolicies((List) Arrays.asList(
new CoreRibbonResizePolicies.None(projetoBand.getControlPanel()),
new CoreRibbonResizePolicies.None(projetoBand.getControlPanel()),
new IconRibbonBandResizePolicy(projetoBand.getControlPanel())));
btnVolumeNovoCenario = new JCommandButton(null, getResizableIconFromResource("newvolscenario.png"));
btnVolumeNovoCenario.setActionRichTooltip(new RichTooltip("Cenário", "Cria um novo cenário"));
btnVolumeNovoCenario.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
novoCenarioVolume();
}
});
btnVolumeDuplicarCenario = new JCommandButton(null, getResizableIconFromResource("dupCenarioVolume.png"));
btnVolumeDuplicarCenario.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
DuplicarCenarioPresenter dpCenario = new DuplicarCenarioPresenter(Main.this);
}
});
volumeBand.addCommandButton(btnVolumeNovoCenario, RibbonElementPriority.TOP);
volumeBand.addCommandButton(btnVolumeDuplicarCenario, RibbonElementPriority.TOP);
JRibbonBand indLocalBand = new JRibbonBand("Índice de Local", getResizableIconFromResource("exit.png"));
btnIndLocalNovoCenario = new JCommandButton(null, getResizableIconFromResource("newilscenario.png"));
btnIndLocalNovoCenario.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
iLocal++;
IconNode node = new IconNode("Cenário " + iLocal, true, new ImageIcon(Configuracao.getPath() + "images/cenario4.png"), IconNode.CENARIO_INDICELOCAL);
addNode("Índice de Local", node);
}
});
indLocalBand.addCommandButton(btnIndLocalNovoCenario, RibbonElementPriority.LOW);
indLocalBand.setPreferredSize(new Dimension(100, 100));
indLocalBand.setResizePolicies((List) Arrays.asList(
new CoreRibbonResizePolicies.None(projetoBand.getControlPanel()),
new IconRibbonBandResizePolicy(projetoBand.getControlPanel())));
JRibbonBand dadosBand = new JRibbonBand("world!", null);
dadosBand.setResizePolicies((List) Arrays.asList(new IconRibbonBandResizePolicy(dadosBand.getControlPanel())));
JRibbonBand configuracoesBand = new JRibbonBand("Configurações", null);
configuracoesBand.setResizePolicies((List) Arrays.asList(
new CoreRibbonResizePolicies.None(configuracoesBand.getControlPanel())));
JCommandButton btnConfiguracoes = new JCommandButton(null, getResizableIconFromResource("settings.png"));
btnConfiguracoes.setActionRichTooltip(new RichTooltip("Configurações", "Permite alterar as configurações do sistema"));
btnConfiguracoes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ConfiguracoesView configuracoes = new ConfiguracoesView(null, true);
configuracoes.setVisible(true);
}
});
configuracoesBand.addCommandButton(btnConfiguracoes, RibbonElementPriority.TOP);
JRibbonBand janelaBand = new JRibbonBand("Organizar", getResizableIconFromResource("exit.png"));
janelaBand.setResizePolicies((List) Arrays.asList(
new CoreRibbonResizePolicies.None(janelaBand.getControlPanel()),
new CoreRibbonResizePolicies.None(janelaBand.getControlPanel()),
new IconRibbonBandResizePolicy(janelaBand.getControlPanel())));
JCommandButton btnLadoALado = new JCommandButton(null, getResizableIconFromResource("tile_vertical.png"));
JCommandButton btnCascata = new JCommandButton(null, getResizableIconFromResource("cascade.png"));
btnLadoALado.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
desktop.tileFrames();
}
});
btnCascata.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
desktop.cascadeFrames();
}
});
janelaBand.addCommandButton(btnLadoALado, RibbonElementPriority.MEDIUM);
janelaBand.addCommandButton(btnCascata, RibbonElementPriority.MEDIUM);
JRibbonBand modeloBand = new JRibbonBand("Modelos", getResizableIconFromResource("models.png"));
modeloBand.setResizePolicies((List) Arrays.asList(
new CoreRibbonResizePolicies.None(janelaBand.getControlPanel()),
new IconRibbonBandResizePolicy(janelaBand.getControlPanel())));
JCommandButton btnManterModelos = new JCommandButton(null, getResizableIconFromResource("models.png"));
btnManterModelos.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mantemModelos();
}
});
modeloBand.addCommandButton(btnManterModelos, RibbonElementPriority.MEDIUM);
JRibbonBand bands[] = new JRibbonBand[4];
bands[0] = projetoBand;
bands[1] = volumeBand;
bands[2] = indLocalBand;
bands[3] = modeloBand;
RibbonTask tskProjeto = new RibbonTask("Principal", bands);
RibbonTask tskDados = new RibbonTask("Dados", dadosBand);
RibbonTask tskFerramentas = new RibbonTask("Ferramentas", configuracoesBand);
RibbonTask tskJanela = new RibbonTask("Janela", janelaBand);
this.getRibbon().addTask(tskProjeto);
this.getRibbon().addTask(tskDados);
this.getRibbon().addTask(tskFerramentas);
this.getRibbon().addTask(tskJanela);
JMenuBar aMenuBar = new JMenuBar();
JMenu aMenu = new JMenu("Arquivo");
JMenuItem aMenuItem = new JMenuItem("Sair");
aMenuItem.setIcon(new ImageIcon(Configuracao.getPath() + "images/exit.png"));
aMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fechar();
}
});
aMenu.add(aMenuItem);
aMenuBar.add(aMenu);
this.getRibbon().addTaskbarComponent(aMenuBar);
this.getRibbon().setPreferredSize(new Dimension(getRibbon().getWidth(), 125));
this.getRibbon().setMaximumSize(new Dimension(getRibbon().getWidth(), 125));
}
private void initComponents() {
try {
this.setTitle("Mensuração Florestal");
splMain = new JSplitPane();
scrNavigator = new JScrollPane();
treeNavigator = new JXTree();
stbMain = new JXStatusBar();
desktop = new MDIDeskTopPane();
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
splMain.setDividerSize(4);
DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode("root");
treeNavigator.setModel(new DefaultTreeModel(treeNode1));
treeNavigator.setRowHeight(18);
scrNavigator.setViewportView(treeNavigator);
double resize = Configuracao.getResizeWeight();
if (Configuracao.getResizeWeight() == 0) {
resize = 0.15;
}
splMain.setResizeWeight(resize);
splMain.setRightComponent(desktop);
splMain.setLeftComponent(scrNavigator);
GroupLayout layout = new GroupLayout(getContentPane());
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(
stbMain, GroupLayout.DEFAULT_SIZE, 1146, Short.MAX_VALUE).addComponent(
splMain, GroupLayout.DEFAULT_SIZE, 1146, Short.MAX_VALUE));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
layout.createSequentialGroup().addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(
splMain, GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE).addPreferredGap(
LayoutStyle.ComponentPlacement.RELATED).addComponent(
stbMain, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE).addContainerGap()));
add(stbMain, BorderLayout.SOUTH);
ImageIcon icone = new ImageIcon(Configuracao.getPath() + "images/app.png");
setIconImage(icone.getImage());
createStatusBar();
createToolbar();
setViewState(new ProjetoFechado(this));
createTree();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
fechar();
}
});
Dimension resolucao = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) Math.round(resolucao.width - (resolucao.width * 0.05));
int height = (int) Math.round(resolucao.height - (resolucao.height * 0.05));
setSize(width, height);
new Thread() {
@Override
public void run() {
new SplashView(Main.this);
}
}.start();
setLocationRelativeTo(null);
if (Configuracao.isMaximized()) {
setExtendedState(MAXIMIZED_BOTH);
}
for (int i = 0; i < getRibbon().getTaskCount(); i++) {
for (int j = 0; j < getRibbon().getTask(i).getBandCount(); j++) {
getRibbon().getTask(i).getBand(j).addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
state.doEntry();
}
});
}
}
} catch (Exception ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(Main.this, info);
}
}
private void createStatusBar() {
stbMain.add(new JLabel("Pronto"), JXStatusBar.Constraint.ResizeBehavior.FILL);
}
private void addNode(String nodeName, IconNode icFilho) {
IconNode icRoot = (IconNode) treeNavigator.getModel().getRoot();
for (int i = 0; i < icRoot.getChildCount(); i++) {
IconNode icNode = ((IconNode) icRoot.getChildAt(i));
if (icNode.getUserObject().toString().equals(nodeName)) {
icNode.add(icFilho);
treeNavigator.updateUI();
treeNavigator.expandAll();
}
}
}
private ResizableIcon getResizableIconFromResource(String resource) {
return ImageWrapperResizableIcon.getIcon(
new ImageIcon(Configuracao.getPath() + "images/" + resource).getImage(), new Dimension(16, 16));
}
public Projeto getProjeto() {
return projeto;
}
public ProjetoDAO getProjetoDAO() {
return projetoDAO;
}
private void novoCenarioVolume() {
CenarioVolumePresenter cenarioVolume = new CenarioVolumePresenter(this);
cenarioVolume.setStrategy(new InclusaoCenario(cenarioVolume.getView()));
activePanel(cenarioVolume.getView());
}
private void mantemModelos() {
try {
new ModelosPresenter();
} catch (Exception ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(null, info);
}
}
public AbstractMainState getViewState() {
return this.state;
}
public void setViewState(AbstractMainState state) {
this.state = state;
}
public JCommandButton getBtnFecharProjeto() {
return btnFecharProjeto;
}
public JCommandButton getBtnNovoProjeto() {
return btnNovoProjeto;
}
public JCommandButton getBtnVolumeDuplicarCenario() {
return btnVolumeDuplicarCenario;
}
public JCommandButton getBtnIndLocalNovoCenario() {
return btnIndLocalNovoCenario;
}
public JCommandButton getBtnVolumeNovoCenario() {
return btnVolumeNovoCenario;
}
public JXStatusBar getStbMain() {
return stbMain;
}
public JXTree getTreeNavigator() {
return treeNavigator;
}
public MDIDeskTopPane getDesktop() {
return desktop;
}
public JSplitPane getSplMain() {
return splMain;
}
public JCommandButton getBtnAbrirProjeto() {
return btnAbrirProjeto;
}
private void fechar() {
try {
state.fechar();
} catch (IOException ex) {
ErrorInfo info = new ErrorInfo("Erro", ex.getMessage(), null, "category", ex, Level.SEVERE, null);
JXErrorPane.showDialog(Main.this, info);
}
}
public void abreProjeto(Projeto projeto) {
this.projeto = projeto;
state.abrirProjeto();
}
private void novoProjeto() {
ProjetoPresenter projetoPresenter = new ProjetoPresenter(this);
projetoPresenter.setStrategy(new InclusaoProjeto(projetoPresenter.getView()));
activePanel(projetoPresenter.getView());
}
public void setProjeto(Projeto projeto) {
this.projeto = projeto;
}
private boolean containsMenuItem(String nome) {
for (Object object : menuTree.getComponents()) {
if (object instanceof JMenuItem) {
if (((JMenuItem) object).getText().equals(nome)) {
return true;
}
}
}
return false;
}
private void removeMenuItem(String nome) {
for (Object object : menuTree.getComponents()) {
if (object instanceof JMenuItem) {
if (((JMenuItem) object).getText().equals(nome)) {
menuTree.remove((JMenuItem) object);
}
}
}
}
private void removeFrameVolume() {
for (JInternalFrame frame : desktop.getAllFrames()) {
if (frame instanceof CenarioVolumeView) {
frame.setVisible(false);
frame.dispose();
desktop.remove(frame);
break;
}
}
}
}