// UML Model Transformation Tool (UMT)
// Copyright (C) 2003, 2004, 2005 SINTEF
// Authors: jon.oldevik at sintef.no | roy.gronmo at sintef.no | tor.neple at sintef.no | fredrik.vraalsen at sintef.no
// Webpage: http://umt.sourceforge.net
// Deloped in the projects: ACEGIS (EU project - IST-2002-37724),
// CAFE (EUREKA/ITEA - ip00004), FAMILIES (ITEA project ip02009)
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2.1
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
// 02111-1307 USA
/**
*
* The UMTMain class contains various GUI initiation stuff,
* startup routines and utilities...
*
*/
package org.sintef.umt.umtmain;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.InputSource;
import org.sintef.umt.project.ProjectEditor;
import org.sintef.umt.project.ProjectListener;
import org.sintef.umt.project.ProjectManager;
import org.sintef.umt.propertyeditor.ProfileEditor;
import org.sintef.umt.propertyeditor.PropertyEditor;
import org.sintef.umt.propertyeditor.PropertyGroup;
import org.sintef.umt.propertyeditor.TransformationEditor;
import org.sintef.umt.systemfamily.SystemFamilyWorkContext;
import org.sintef.umt.transformer.DefaultReverseTransformer;
import org.sintef.umt.transformer.TransformationResultListener;
import org.sintef.umt.transformer.TransformerEngine;
import org.sintef.umt.transformer.TransformerEngineFactory;
import org.sintef.umt.transformer.XMLUtility;
import org.sintef.umt.transgen.DOMXmiSchema;
import org.sintef.umt.transgen.Profile2XSD;
import org.sintef.umt.transgen.Validator;
import org.sintef.umt.transgen.XmiSchema;
import org.sintef.umt.utils.FileUtils;
import org.sintef.umt.utils.UmtFileFilter;
import org.sintef.umt.utils.UriViewer;
import org.sintef.umt.utils.UriViewerListener;
import org.w3c.dom.*;
import java.io.*;
import java.net.URI;
import java.util.*;
public class UMTMain extends JFrame implements ActionListener, UriViewerListener, ResourceLoadListener
{
public static String docs_dir = null;
public static String resource_dir = null;
public static String config_dir = null;
public static String img_dir = null;
public static String family_img_dir = null;
public static int RUNTIME_STANDALONE = 0;
public static int RUNTIME_EMBEDDED = 1;
private static int _runtime_environment = RUNTIME_STANDALONE;
public final static int UMT_STANDARD = 0;
public final static int UMT_SYSTEM_FAMILY = 1;
private static int _umt_type = UMT_STANDARD;
private static int MODEL_TAB_INDEX = 0;
private static int PROJECT_TAB_INDEX = 1;
private static int RESULT_TAB_INDEX = 2;
private final static String title = "";
ResourceBundle resourceBundle = null;
private JTabbedPane tab;
private static OutputWindow output;
private FileViewer fileviewer;
private PIMViewer pimviewer;
private static ProfileEditor profileeditor = null;
private static TransformationEditor transformationeditor = null;
private static TransformationActionListener transformationActionListener = null;
private volatile String _last_transformation = null;
private JButton transformation_button = null;
private static ProjectManager projectmanager;
private Element _transformationcontext;
private JMenu recent_menu;
private JButton refresh_button = null;
private Vector recent_files;
private static String current_open_dir, current_store_dir;
private String current_source = null;
private static String recent_file_name = null;
private static String preference_file = null;
public static ImageIcon appicon = null;
private JMenu forward_transformationmenu, reverse_transformationmenu;
private static WorkContext _workcontext;
private Vector project_menuitems = null; /* Menuitems that are only active when a project is open */
private Vector model_menuitems = null; /* Menuitems that are only active when a model is loaded - includes implicitly includes project menuitems */
private Reader _modelreader = null;
private java.util.zip.ZipFile _zipfile = null;
private static JFileChooser chooser = null;
private static ResourceBundle umtBundle = null;
/**
*
* @param args
* @param apptype (either systemfamily or anything/nothing)
* @throws Exception
*/
public UMTMain (String[] args, String apptype) throws Exception {
super (title);
if (apptype != null && apptype.equalsIgnoreCase("systemfamily"))
_umt_type = UMTMain.UMT_SYSTEM_FAMILY;
try {
init ();
checkArgs (args);
repaint ();
} catch (Exception ex) {
throw ex;
}
}
public UMTMain (String[] args, int runtime_env) throws Exception {
super (title);
try {
init ();
checkArgs (args);
repaint ();
_runtime_environment = runtime_env;
} catch (Exception ex) {
throw ex;
}
}
public static String getResourceName (String id) {
if (umtBundle != null)
return umtBundle.getString(id);
else
return id;
}
//
// Look and Feel
//
static String[] lafNames = {"Windows", "Metal", "Motif"};
static String[] lafClasses = {"com.sun.java.swing.plaf.windows.WindowsLookAndFeel",
"javax.swing.plaf.metal.MetalLookAndFeel",
"com.sun.java.swing.plaf.motif.MotifLookAndFeel",
"javax.swing.plaf.basic.BasicLookAndFeel",
"javax.swing.plaf.basic.MultiLookAndFeel"};
/**
*
* Initiates the tools, defines layout, menus, etc.
*
*/
public void init () throws Exception {
if (resource_dir == null)
setRootDirectory ("..");
loadResources ();
appicon = _umt_type==UMTMain.UMT_SYSTEM_FAMILY?new ImageIcon (family_img_dir + "appicon.gif"):new ImageIcon(img_dir + "appicon.gif");
UmtSplash splasher = null;
try {
splasher = new UmtSplash ();
} catch (Exception ex) {
System.out.println ("UMTMain::init () - " + ex);
throw (ex);
}
try {
setIconImage(appicon.getImage());
} catch (Exception ex) {
System.out.println ("UMTMain::init () - " + ex);
throw (ex);
}
defineMenuBar();
try {
/*
* THE LAYOUT
*/
Container c = getContentPane ();
// c.setLayout (new GridLayout (1,1));
c.setLayout (new BorderLayout ());
output = new OutputWindow ();
Dimension outputdim = new Dimension (100, 150);
/*output.setPreferredSize(outputdim);
output.setSize(outputdim);
*/
tab = new JTabbedPane ();
tab.addChangeListener(new TabChangeListener ());
fileviewer = new FileViewer ();
/*
* Profile Editor inititation
*/
profileeditor = new ProfileEditor ();
/*
* Transformation Editor initiation
*/
transformationeditor = new TransformationEditor ();
String defaultview = UMTMain.getProperty("umt.defaultview");
_workcontext = _umt_type == UMT_SYSTEM_FAMILY? new SystemFamilyWorkContext (): new WorkContext();
pimviewer = new PIMViewer (output);
_workcontext.addWorkContextListener(pimviewer);
pimviewer.setUMTMain(this);
if (defaultview.equalsIgnoreCase("infoview"))
pimviewer.setInfoMode();
else
pimviewer.setModelMode();
pimviewer.setUriViewerListener(this);
// pimviewer.setPreferredSize (new Dimension(500,500));
tab.add("Model Viewer", pimviewer);
tab.setToolTipTextAt(tab.getComponentCount() - 1, "Model Viewer tab");
tab.add("Project", new JPanel ());
// tab.setComponentAt()
tab.setToolTipTextAt(tab.getComponentCount() - 1, "Project settings/information");
tab.setEnabledAt(tab.getComponentCount() - 1, false);
tab.add("Results...", fileviewer);
tab.setToolTipTextAt(tab.getComponentCount() - 1, "Results from transformations");
tab.setEnabledAt(tab.getComponentCount() - 1, false);
// tab.setEnabledAt(tab.getComponentCount() - 1, false);
JSplitPane split = new JSplitPane (JSplitPane.VERTICAL_SPLIT);
split.setLeftComponent(tab);
split.setRightComponent(output);
split.setContinuousLayout(false);
split.setDividerLocation(550);
split.setDividerSize(5);
split.setResizeWeight(1);
c.add(split);
// c.add (tab, BorderLayout.CENTER);
// c.add (output, BorderLayout.SOUTH);
current_open_dir = UMTMain.getProperty("umt.default.dir.open");
if (current_open_dir == null || current_open_dir.equals(""))
current_open_dir = System.getProperty("user.dir");
current_store_dir = UMTMain.getProperty("umt.default.dir.save");
if (current_store_dir == null || current_store_dir.equals(""))
current_store_dir = System.getProperty("user.dir");
setLaf(lafClasses[0]);
recent_files = new Vector ();
loadRecentFiles ();
projectmanager = new ProjectManager (this, pimviewer);
projectmanager.addProjectListener(new ProjectEventListener ());
transformationActionListener = new TransformationActionListener ();
splasher.finish();
XMLUtility.setXMLProperties();
setMenuEnabled (project_menuitems, false);
setMenuEnabled (model_menuitems, false);
} catch (Exception ex) {
System.out.println ("UMTMain::init () - " + ex);
ex.printStackTrace();
throw (ex);
}
}
/**
* Defines the menus
*
*/
private void defineMenuBar () {
try {
ProjectActionListener projectlistener = new ProjectActionListener ();
project_menuitems = new Vector ();
model_menuitems = new Vector ();
// MenuBar creation
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu ("File");
menu.setMnemonic ('F');
JMenu menu2;
menu.setIcon(new ImageIcon(img_dir + "menu.file.gif"));
menu2 = new JMenu ("New");
menu.add(menu2);
menu2.setMnemonic('N');
JMenuItem item = new JMenuItem ("Project");
item.setMnemonic('P');
item.setToolTipText("Create new project");
item.setActionCommand("New");
item.addActionListener(projectlistener);
menu2.add(item);
menu2 = new JMenu ("Open");
menu.add(menu2);
menu2.setMnemonic('O');
final Icon pfIcon = new ImageIcon (family_img_dir + "productFamily.gif");
item = new JMenuItem ("Project");
item.setMnemonic('P');
item.setToolTipText("Opens an existing Project");
item.setActionCommand("Open");
item.addActionListener(projectlistener);
menu2.add(item);
if (_umt_type == UMT_SYSTEM_FAMILY) {
item.setText("Product Line Project");
item.setIcon(pfIcon);
}
item = new JMenuItem ("XMI|XMI Light as new project");
item.addActionListener (this);
item.setToolTipText ("Opens an XMI or an XMI Light file and creates a new project associated with it.");
item.setActionCommand ("open xmi project");
menu2.add (item);
if (_umt_type == UMT_SYSTEM_FAMILY) {
item.setText("Product Line As New Project");
item.setIcon(pfIcon);
}
if (_umt_type == UMT_STANDARD) {
item = new JMenuItem ("XMI or XMI Light file");
item.addActionListener (this);
item.setToolTipText("Opens an XMI or an XMI Light file (also .zuml/.zargo/.zip files)");
item.setActionCommand ("open xmi");
menu2.add(item);
}
/*
* System Family menu items
*/
if (_umt_type == UMT_SYSTEM_FAMILY) {
item = new JMenuItem ("Product Line Model");
item.addActionListener (this);
item.setToolTipText("Opens a Product Line Model XMI/XMI Light file");
item.setActionCommand ("open-product-line");
item.setIcon(pfIcon);
menu2.add(item);
item = new JMenuItem ("Product/System Model");
item.addActionListener (this);
item.setToolTipText("Opens a Product Model XMI/XMI Light file");
item.setIcon(new ImageIcon (family_img_dir + "productFolder.gif"));
item.setActionCommand ("open-product");
menu2.add(item);
}
menu2 = new JMenu ("Save");
menu.add(menu2);
menu2.setMnemonic('S');
item = new JMenuItem ("Save XMI-Light");
item.setMnemonic('L');
item.setToolTipText ("Saves the current model's XMI Light representation.");
item.addActionListener (this);
menu2.add(item);
item = new JMenuItem ("Save as XMI");
item.setMnemonic('X');
item.setToolTipText("Saves XMI Light as XMI v1.1");
item.addActionListener (this);
menu2.add(item);
item = new JMenuItem ("Save Settings");
item.setActionCommand ("Save Settings");
item.setMnemonic('S');
item.setToolTipText("Save current tool settings.");
item.addActionListener(this);
menu2 = new JMenu ("Close");
menu2.setMnemonic('C');
item = new JMenuItem ("Project");
item.setMnemonic('P');
item.setActionCommand("Close");
item.setToolTipText("Closes the project that is currently open....");
item.addActionListener(projectlistener);
menu2.add(item);
project_menuitems.add(menu2);
menu.add(menu2);
menu2 = new JMenu ("Delete");
menu2.setMnemonic('D');
item = new JMenuItem ("Delete current project");
item.setMnemonic('P');
item.setActionCommand("Delete_current");
item.setToolTipText("Delete current project.");
item.addActionListener(projectlistener);
project_menuitems.add(item);
menu2.add(item);
item = new JMenuItem ("A Project");
item.setMnemonic('P');
item.setActionCommand("Delete");
item.setToolTipText("Delete a project from the project list.");
item.addActionListener(projectlistener);
menu2.add(item);
menu.add(menu2);
item = new JMenuItem ("Exit");
item.addActionListener (this);
item.setMnemonic ('E');
menu.add(item);
menu.add(new JSeparator());
recent_menu = new JMenu ("Recent files...");
recent_menu.setMnemonic('R');
menu.add (recent_menu);
menubar.add(menu);
/*
* Settings Menu
*/
menu = new JMenu ("Settings");
menu.setMnemonic('S');
menu.setIcon(new ImageIcon(img_dir + "menu.settings.gif"));
menubar.add(menu);
item = new JMenuItem ("Transformations");
item.setMnemonic('T');
item.setToolTipText("Edit available transformations");
item.addActionListener(this);
menu.add(item);
item = new JMenuItem ("Profiles");
item.setMnemonic('r');
item.setToolTipText("Edit available profiles");
item.addActionListener(this);
menu.add(item);
item = new JMenuItem ("Preferences");
item.setMnemonic('P');
item.setToolTipText("Edit general UMT preferences");
item.addActionListener(this);
menu.add(item);
/*
* PROJECT Menu
*/
/*
menu = new JMenu ("Project");
menu.setMnemonic('P');
item = new JMenuItem ("Settings");
item.setMnemonic('S');
item.setToolTipText("View/Edit the project settings.");
item.addActionListener(projectlistener);
menu.add(item);
*/
/*
*
item = new JMenuItem ("Set Profile");
item.setMnemonic('P');
item.addActionListener(projectlistener);
item.setToolTipText("Sets the profile for this project");
menu.add (item);
menubar.add(menu);
project_menuitems.add(menu);
*/
/*
* TRANSFORMATION MENU
*/
menu = new JMenu ("Transformation");
menu.setMnemonic('T');
menu.setIcon(new ImageIcon(img_dir + "menu.transformation.gif"));
menubar.add(menu);
UmtMenuListener umt_menulistener = new UmtMenuListener ();
menu2 = new JMenu ("Forward transformation");
menu2.setActionCommand("Forward_transformation");
menu2.addMenuListener(umt_menulistener);
menu2.setMnemonic('F');
menu.add (menu2);
forward_transformationmenu = menu2;
model_menuitems.add(menu2);
menu2 = new JMenu ("Reverse transformation");
menu2.setActionCommand("Reverse_transformation");
menu2.addMenuListener(umt_menulistener);
menu2.setMnemonic('R');
menu.add (menu2);
reverse_transformationmenu = menu2;
/*
* PROFILES MENU
*/
menu = new JMenu("Profiles");
menu.setMnemonic('P');
menu.setIcon(new ImageIcon(img_dir + "menu.profiles.gif"));
item = new JMenuItem("Check adherence to profile");
item.setActionCommand("Check_adherence_to_profile");
item.setMnemonic('C');
item.addActionListener(this);
menu.add(item);
item = new JMenuItem("Assign profile");
item.setActionCommand("Assign_Profile");
item.setEnabled(true);
item.setMnemonic('A');
item.addActionListener(this);
// item.disable();
menu.add(item);
model_menuitems.add(menu);
menubar.add(menu);
/*
* System Family Menu (2)
*/
if (_umt_type == UMT_SYSTEM_FAMILY) {
menu = new JMenu ("Product Line");
menu.setMnemonic('y');
menu.setIcon(new ImageIcon(img_dir + "menu.families.gif"));
menu2 = new JMenu ("Check Family Model");
menu2.setMnemonic('C');
// menu2.addActionListener (this);
menu.add(menu2);
menubar.add(menu);
}
/*
* VIEW MENU
*/
menu = new JMenu ("View");
menu.setMnemonic('V');
menu.setIcon(new ImageIcon(img_dir + "menu.view.gif"));
menu2 = new JMenu ("Windows");
menu2.setEnabled(true);
menu2.setMnemonic('W');
item = new JMenuItem ("Xmi Light view");
item.setMnemonic('X');
item.addActionListener(this);
menu2.add(item);
item = new JMenuItem ("Information view");
item.setMnemonic('I');
item.addActionListener(this);
menu2.add(item);
if (_umt_type == UMT_SYSTEM_FAMILY) {
item = new JMenuItem ("Product Line view");
item.setActionCommand("Product_Line_View");
item.setMnemonic('S');
item.addActionListener(this);
menu2.add(item);
}
menu.add (menu2);
menu2 = new JMenu ("LookAndFeel");
LafChangeActionListener lafListener = new LafChangeActionListener();
for (int i = 0; i < lafNames.length;i++){
item = new JMenuItem(lafNames[i]);
item.addActionListener (lafListener);
menu2.add(item);
}
menu.add(menu2);
menubar.add(menu);
/*
Help Menu
*/
menu = new JMenu ("Help");
menu.setMnemonic('H');
menu.setIcon(new ImageIcon(img_dir + "menu.help.gif"));
item = new JMenuItem ("About");
item.addActionListener (this);
menu.add (item);
item = new JMenuItem ("Tool help");
item.addActionListener (this);
menu.add (item);
item = new JMenuItem ("Developers guide");
item.addActionListener (this);
menu.add (item);
menubar.add(menu);
menubar.add(new JLabel (" "));
// Some Utility buttons
refresh_button = new JButton (new ImageIcon(img_dir + "redo.gif"));
refresh_button.setRolloverEnabled(true);
refresh_button.setRolloverIcon(new ImageIcon(img_dir + "undo.gif"));
refresh_button.setToolTipText("Reload the current source");
refresh_button.setActionCommand("RefreshSource");
refresh_button.addActionListener(this);
refresh_button.setOpaque(true);
refresh_button.setBorderPainted(false);
menubar.add(refresh_button);
model_menuitems.add(refresh_button);
transformation_button = new JButton (new ImageIcon(img_dir + "execute.gif"));
transformation_button.setRolloverEnabled(true);
transformation_button.setRolloverIcon(new ImageIcon(img_dir + "execute_rollover.gif"));
transformation_button.setToolTipText("Execute the previous transformation (" + _last_transformation + ")");
transformation_button.setActionCommand("ExecuteTransformation");
transformation_button.addActionListener(this);
transformation_button.setOpaque(true);
transformation_button.setBorderPainted(false);
transformation_button.setEnabled(false);
menubar.add(transformation_button);
setJMenuBar (menubar);
} catch (Exception ex) {
}
}
/**
* Loads resources from file
*/
private void loadResources () {
Properties resources = new Properties();
FileInputStream is = null;
try {
umtBundle = ResourceBundle.getBundle("org.sintef.umt.umtmain.UMTResources");
} catch (Exception ex) {
}
try {
if (_umt_type == UMTMain.UMT_SYSTEM_FAMILY) {
is = new FileInputStream (UMTMain.config_dir + "umt.families.properties");
resources.load(is);
}
else {
is = new FileInputStream (UMTMain.config_dir + "umt.properties");
resources.load(is);
}
this.setTitle(resources.getProperty("umt.title"));
is.close();
} catch (Exception ex) {
System.out.println ("UMTMain::loadResources:" + ex);
}
is = null;
}
/**
* Iterate and handle application input parameters
* Parameters:
* -pim <pim filename> --> startup UMT with this PIM file
* -xmi <xmi filename> --> startup UMT with this XMI file
*/
private void checkArgs (String[] args) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase ("-pim")) {
if (args.length < 2)
System.out.println ("UMT startup command '" + args[0] + "' - missing additional parameter.");
else {
doOpenAnyFile (new File(args[1]), false, "class");
}
} else if (args[0].equalsIgnoreCase("-xmi")) {
if (args.length < 2)
System.out.println ("UMT startup command '" + args[0] + "' - missing additional parameter.");
else {
doOpenAnyFile (new File(args[1]), false, "class");
}
} else {
System.out.println ("UMT startup command '" + args[0] + "' not understood.");
}
}
}
public static int getUmtType () {
return UMTMain._umt_type;
}
public void setLastTransformation (String transformation) {
// enable the last transformation button
_last_transformation = transformation;
transformation_button.setToolTipText("Execute the previous transformation (" + _last_transformation + ")");
transformation_button.setEnabled(true);
}
/**
*
* Sets the root directory and defines the relateve paths
*
*/
public static void setRootDirectory (String umt_root_dir) {
docs_dir = umt_root_dir + System.getProperty("file.separator") + "docs" + System.getProperty("file.separator");
resource_dir = umt_root_dir + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator");
config_dir = resource_dir + System.getProperty("file.separator") + "config" + System.getProperty("file.separator");
img_dir = resource_dir + System.getProperty("file.separator") + "img" + System.getProperty("file.separator");
family_img_dir = img_dir + System.getProperty("file.separator") + "systemFamily" + System.getProperty("file.separator");
recent_file_name = config_dir + "recent_files.config";
preference_file = config_dir + "preferences.xml";
}
private void setMenuEnabled (Vector menuitems, boolean enabled) {
for (Enumeration _enum = menuitems.elements(); _enum.hasMoreElements();){
JComponent item = (JComponent)_enum.nextElement();
item.setEnabled(enabled);
}
}
/**
*
* Validates the loaded model towards the profile chosen
*
*/
private void doValidateModel(){
pimviewer.clearLineColors();
output.addLine("Validation : initializing");
Validator theValidator = new Validator(output);
XmiSchema theSchema = new DOMXmiSchema(UMTMain.resource_dir + "extxmi.xsd");
PropertyGroup theProfile = profileeditor.getChosenProfile();
Profile2XSD transformer = new Profile2XSD();
try{
DocumentBuilderFactory theFact = DocumentBuilderFactory.newInstance();
DocumentBuilder bobTheBuilder = theFact.newDocumentBuilder();
InputSource toParse = new InputSource(new StringReader(pimviewer.getHutnBuffer()));
Document theModel = bobTheBuilder.parse(toParse);
theSchema = transformer.doTransformation(theProfile,theModel);
String theProfileName = "No profile selected.";
if (theProfile != null)
theProfileName = theProfile.getName();
if (theProfileName == null || theProfileName.equals(""))
theProfileName = "(no profile)";
output.addLine("Validation : starting validation. Profile = " + theProfileName);
theValidator.validateAgainstSchema(theModel,theSchema);
output.addLine("Validation : validation done") ;
Iterator it = output.getErrorLines().iterator();
while (it.hasNext())
pimviewer.colorTextLine(((Integer)it.next()).intValue());
}
catch(Exception e){
System.out.println(e);
}
}
/**
*
* Handles all actions from the menu that are not handled by specialised
* action handlers
*
*/
public void actionPerformed (ActionEvent ae){
output.clear();
String action = ae.getActionCommand ();
/* System.out.println(action); */
if (action.equalsIgnoreCase ("Check_adherence_to_profile")){
doValidateModel();
} else if (action.equalsIgnoreCase("Assign_Profile")){
System.out.println ("Assign profile");
launchProfileSelector();
} else if (action.equalsIgnoreCase ("Open configuration")){
// doOpenConfiguration ();
}else if (action.equalsIgnoreCase ("Save as new configuration")){
// doSaveConfiguration ();
} else if (action.equalsIgnoreCase ("Information view")) {
pimviewer.setInfoMode();
} else if (action.equalsIgnoreCase ("XMI Light view")) {
pimviewer.setModelMode();
} else if (action.equalsIgnoreCase("Product_Line_View")) {
pimviewer.setSystemFamilyMode();
} else if (action.equalsIgnoreCase ("Exit")){
finish ();
if (_runtime_environment == RUNTIME_STANDALONE)
System.exit (1);
else
this.setVisible(false);
} else if (action.equalsIgnoreCase ("open xmi")){
projectmanager.saveProject();
doOpenFile ("xmi", false);
} else if (action.equalsIgnoreCase ("open xmi project")) {
projectmanager.saveProject();
doOpenFile ("xmi", true);
} else if (action.equalsIgnoreCase ("save XMI-Light")) {
doSaveFile ("pim");
} else if (action.equalsIgnoreCase("Save as xmi")) {
doSaveFile ("xmi");
} else if (action.equalsIgnoreCase("Save Settings")) {
this.storeSettings();
} else if (action.equalsIgnoreCase ("Open Recent")) {
projectmanager.saveProject();
String filename = ((JMenuItem)ae.getSource()).getToolTipText();
openSelectedFile (filename);
} else if (action.equalsIgnoreCase("About")) {
UriViewer viewer = new UriViewer ("About", true);
viewer.setFile(docs_dir + "about.html");
} else if (action.equalsIgnoreCase("tool help")) {
UriViewer viewer = new UriViewer ("Tool help", true);
viewer.setFile(docs_dir + "index.html");
} else if (action.equalsIgnoreCase("developers guide")) {
UriViewer viewer = new UriViewer ("Developers Guide", true);
viewer.setFile(docs_dir + "developers_guide.html");
} else if (action.equalsIgnoreCase("Transformations")) {
/* Launch transformation editor */
launchEditor (transformationeditor, "Editor Transformations");
} else if (action.equalsIgnoreCase("Profiles")) {
/* Launch profiles editor */
launchEditor (profileeditor, "Edit Profiles");
} else if (action.equalsIgnoreCase("Preferences")) {
showPreferences ();
} else if (action.equalsIgnoreCase("RefreshSource")) {
ProjectEditor pe = projectmanager.getCurrentProject();
if (pe != null) {
projectmanager.doOpenProject(pe.getId());
} else {
if (current_source != null && !(current_source.equals(""))){
openSelectedFile (current_source);
}
}
System.out.println (pe);
System.out.println ("Current Source: " + current_source);
} else if (action.equalsIgnoreCase("ExecuteTransformation")) {
System.out.println ("Execute the previous transformation ....");
if (_last_transformation != null) {
ActionEvent event = new ActionEvent(ae.getSource(), ae.getID(), _last_transformation);
transformationActionListener.actionPerformed(event);
}
}
/*
* System Family actions
*/
else if (action.equalsIgnoreCase("open-product-line")) {
System.out.println ("Open Product Line Model");
doOpenFile ("product-line", false);
} else if (action.equalsIgnoreCase("open-product")) {
System.out.println ("Open Product Model");
doOpenFile ("xmi", false);
}
/*
* End System Family Actions
*/
}
/**
* Launches a simple selector for selecting a profile
*/
private void launchProfileSelector () {
try {
String[] profiles = UMTMain.getProfileNames();
Object result = JOptionPane.showInputDialog(this, "Select Profile", "Profile Selector", JOptionPane.PLAIN_MESSAGE, null, profiles, profiles[0]);
System.out.println ("Selected " + result);
if (result != null) {
UMTMain.setActiveProfile((String)result);
output.printLine("Profile selected: " + result);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Launch an editor (e.g. Transformation editor) in a separate window...
*/
private void launchEditor (JPanel editor, String title) {
final JDialog window = new JDialog (this, title, true);
ActionListener listener = new ActionListener () {
public void actionPerformed (ActionEvent action) {
if (action.getActionCommand().equalsIgnoreCase("Close")){
window.setVisible(false);
window.dispose();
}
}
};
window.addWindowListener (new WindowAdapter(){
public void windowClosing (WindowEvent we){
window.dispose();
}
});
JPanel buttonpanel = new JPanel ();
buttonpanel.setLayout(new FlowLayout (FlowLayout.LEFT));
final JButton close = new JButton ("Close");
close.addActionListener(listener);
buttonpanel.add(close);
window.getContentPane().setLayout(new BorderLayout ());
window.getContentPane().add(editor, BorderLayout.CENTER);
window.getContentPane().add(buttonpanel, BorderLayout.SOUTH);
window.setLocation((int) (getX() * 1.1), (int) (getY() * 1.1));
window.setSize(this.getWidth()* 2/3, (this.getHeight())*2/3);
window.setVisible(true);
}
private void doOpenAsProject (File f, String type, boolean isUml2) {
File source = f;
String location = source.getParentFile().getAbsolutePath();
String name = source.getName ();
int dotLoc = name.lastIndexOf('.');
if (dotLoc > -1) {
name = name.substring(0, dotLoc);
}
boolean source_exists = projectmanager.findProjectWithSource(source);
if (source_exists)
System.out.println (" - A project with the source " + source + " Exists.");
// TODO: Check for updates etc.
// The source already has a project -- ask user to open this.. or just open it
projectmanager.createProjectDialog(name,location,source.getAbsolutePath(), type);
ProjectEditor editor = projectmanager.getCurrentProject();
if (editor != null)
projectmanager.doOpenProject(editor.getName());
}
public void doOpenXmiFile (File f, boolean isUml2) {
// TODO: Look for a project using this file as source
// Set that project as the current working project
File absolutefile = new File (f.getAbsolutePath());
output.addLine ("Opening file." + absolutefile.getAbsolutePath());
pimviewer.openXmiFile(absolutefile, isUml2);
}
public void doOpenXmiReader (Reader r) {
output.addLine ("Opening XMI-Reader");
pimviewer.openXmiReader(r);
}
/**
* Opens a PIM / Hutn (XML) file
*
*/
public void doOpenPimFile (File f) {
File absolutefile = new File (f.getAbsolutePath());
output.addLine ("Opening file." + absolutefile.getAbsolutePath());
pimviewer.openHutnFile(absolutefile);
}
/**
* Open's any kind of 'UMT' file, i.e. an XMI, XMI Light or activity file
*
* @return boolean: true if the file is readable for UMT
*/
public boolean doOpenAnyFile (File f, boolean as_project, String modeltype) {
boolean is_zip = false;
boolean is_uml2 = false;
String type = null;
try {
if (f.getName().endsWith(".zuml") || f.getName().endsWith(".zargo") || f.getName().endsWith(".zip")) {
_zipfile = new java.util.zip.ZipFile(f);
_modelreader = FileUtils.extractZipFile (_zipfile);
if (_modelreader != null)
is_zip = true; type = "xmi";
} else if (f.getName().endsWith(".uml2") || f.getName().endsWith(".emx")) {
is_uml2 = true;
type = "xmi";
}
if (!is_zip && !is_uml2) {
_modelreader = new BufferedReader(new FileReader (f));
String line = new String (((BufferedReader)_modelreader).readLine().trim().getBytes("US-ASCII")).toLowerCase();
type = ""; int count = 1;
while ((!type.equalsIgnoreCase("other")) && (!type.equalsIgnoreCase("xmi")) && (!type.equalsIgnoreCase("pim"))){
// System.out.println (line);
if (line.startsWith("<xmi")) {
type = "xmi";
} else if (line.startsWith("<!") || line.startsWith("<?")) {
type = "comment";
} else if (line.startsWith("<model") || line.startsWith("<package") || line.startsWith("<activity")) {
type = "pim";
} else if (line.startsWith("<")) {
type = "other";
}
line = new String (((BufferedReader)_modelreader).readLine().trim().getBytes("US-ASCII")).toLowerCase();
}
_modelreader.close(); _modelreader = null;
}
current_open_dir = f.getParentFile().getAbsolutePath();
if (!type.equalsIgnoreCase("xmi") && !type.equalsIgnoreCase("pim")) {
JOptionPane.showMessageDialog(this, "Could not open file with UMT. Neither XMI nor XMI Light file.");
}
current_source = f.getAbsolutePath();
if (current_store_dir.equalsIgnoreCase(System.getProperty("user.dir")) || current_store_dir.equalsIgnoreCase(UMTMain.getProperty("umt.default.dir.save")))
setCurrentStoreDir (f.getParentFile().getAbsolutePath());
if (!as_project) {
if (is_zip) {
if (modeltype.equalsIgnoreCase("product-line")) {
pimviewer.openSystemFamilyReader(_modelreader);
} else
doOpenXmiReader(_modelreader);
} else if (type.equalsIgnoreCase("xmi")) {
if (modeltype.equalsIgnoreCase("product-line"))
pimviewer.openSystemFamilyFile(f, is_uml2);
else
doOpenXmiFile(f, is_uml2);
}
else if (type.equalsIgnoreCase("pim"))
doOpenPimFile(f);
refresh_button.setToolTipText("Refresh current source [" + f.getName() + "]");
} else {
doOpenAsProject (f, type, is_uml2);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "An error occured when opening file: " + ex.getMessage());
} finally {
// Closing of _modelreader deferred to eventlistener ResourceLoadListener
}
repaint ();
return true;
}
private JFileChooser getFileChooser (String directory) {
if (chooser == null) {
chooser = new JFileChooser (directory);
chooser.setAcceptAllFileFilterUsed(false);
chooser.setFileFilter (new UmtFileFilter ());
} else {
try {
File f = new File (directory);
java.net.URI uri = f.toURI();
chooser.setCurrentDirectory(new File(uri));
} catch (Exception ex) {
System.out.println (this.getClass().getName() + "::getFileChooser:" + ex);
}
}
return chooser;
}
/**
*
* Opens a file (XMI or HUTN or other?) using a FileChooser
*
*
*/
private void doOpenFile (String filetype, boolean as_project)
{
// System.out.println ("Open File " + filetype);
pimviewer.closeView();
projectmanager.closeProject();
chooser = getFileChooser (current_open_dir);
chooser.setName("Open " + filetype.toUpperCase() + " file");
chooser.setToolTipText("Open " + filetype.toUpperCase() + " file");
int ret = -100;
try {
ret = chooser.showOpenDialog(this);
} catch (Exception ex) {
System.out.println ("UMTMain::doOpenFile:Error:" + ex);
}
if(ret == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
// add to list of recent files
addRecentFile (f.getAbsolutePath ());
if (filetype.equalsIgnoreCase("product-line")) {
output.addLine ("Opening product line model:" + f.getAbsolutePath());
doOpenAnyFile (f, as_project, "product-line");
} else {
doOpenAnyFile(f, as_project, "class");
}
if (as_project)
_workcontext.setState(WorkContext.STATE_OPENED_PROJECT);
else {
_workcontext.setState(WorkContext.STATE_OPENED_FILE);
setMenuEnabled (model_menuitems, true);
}
current_open_dir = chooser.getCurrentDirectory().getPath();
}
}
/**
*
* Opens a given filename to the PIMViewer
*
*/
private void openSelectedFile (String filename)
{
pimviewer.closeView();
File f = new File(filename);
if (f.exists()) {
this.doOpenAnyFile(f, false, "class");
setMenuEnabled (model_menuitems, true);
//
// This context change is done only for standard umt here.
// For System FAmily, it is done in the HutnEditor.
//
if (_umt_type == UMT_STANDARD)
_workcontext.setState(WorkContext.STATE_OPENED_FILE);
}
else
JOptionPane.showMessageDialog(this, "Cannot open file " + filename + " - it does not exist.");
}
/**
*
* Saves a PIM (or other) file to disk (repository)
*
*
*/
private void doSaveFile (String filetype)
{
chooser = getFileChooser(current_store_dir);
chooser.setName("Save " + filetype.toUpperCase());
String hutnbuffer = pimviewer.getHutnBuffer ();
int ret = chooser.showSaveDialog(this);
if(ret == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
if (filetype.equalsIgnoreCase("pim")) {
try {
PrintWriter pw = new PrintWriter (new FileWriter (f));
pw.println (hutnbuffer);
pw.close();
} catch (IOException ioex) {
System.out.println (ioex);
}
} else if (filetype.equalsIgnoreCase("xmi")) {
// save as XMI
try {
FileWriter writer = new FileWriter (f);
pimviewer.xmiLight2xmi(writer);
writer.close();
} catch (Exception ex) {
System.out.println ("UMTMain::doSaveFile() - " + ex);
}
}
else {
// do nothing at the moment
}
}
}
/**
*
* Loading the buffer of recently used files
* Uses the 'recent_file_name' location
*
*/
private void loadRecentFiles ()
{
Properties props = new Properties ();
try {
props.load(new FileInputStream (new File(recent_file_name)));
} catch (IOException ioex) {
}
for (Enumeration e = props.elements(); e.hasMoreElements ();){
String name = (String)e.nextElement();
recent_files.add(name);
}
initRecentFiles ();
}
/**
*
* Saving the list of recently used files
* Uses the 'recent_file_name' location
*
*/
private void saveRecentFiles ()
{
Properties props = null;
try {
props = new Properties ();
int counter = 1;
for (Enumeration e = recent_files.elements();e.hasMoreElements ();)
{
props.put("f" + counter++, e.nextElement());
}
props.store(new FileOutputStream(new File (recent_file_name)), "Recent files");
} catch (IOException ex) {
}
props = null;
}
/**
*
* Initiates the menu to handle the current 'recent files'
*
*
*/
private void initRecentFiles ()
{
int counter = 1;
recent_menu.removeAll();
JMenuItem item;
for (Enumeration files = recent_files.elements();files.hasMoreElements();){
String name = (String)files.nextElement();
item = new JMenuItem ("[" + counter++ + "] " + name);
item.addActionListener(this);
item.setActionCommand("Open recent");
item.setToolTipText(name);
recent_menu.add (item);
}
}
/**
*
* Adds a recent file to the recent file buffer
*
*/
private void addRecentFile (String filename)
{
if (!recent_files.contains(filename))
{
recent_files.add(0, filename);
if (recent_files.size() > 4)
recent_files.remove(recent_files.size() - 1);
initRecentFiles ();
}
}
/**
* Opens an editor for user/tool preferences.
*/
private void showPreferences () {
PropertyEditor editor = new PropertyEditor (preference_file);
editor.setHeadings("Property name", "Property value");
editor.setNameEditable(false);
editor.setProperties("Preferences","","");
launchEditor (editor, "Edit Preferences");
editor.getPropertyManager().storeProperties();
}
/**
*
* @param property
* @return
*/
public static String getProperty (String property) {
try {
PropertyEditor editor = new PropertyEditor (preference_file);
PropertyGroup pg = editor.getPropertyManager().getPropertyGroupForItem("Preferences");
return pg.getProperty(property);
} catch (Exception ex) {
return "";
}
}
/**
* Get the current project name
*
*/
public static String getProjectName () {
ProjectEditor project_editor = null;
if (projectmanager != null)
project_editor = projectmanager.getCurrentProject();
if (project_editor != null)
return project_editor.getName();
return "";
}
/**
* Get the current project location
*/
public static String getProjectLocation () {
ProjectEditor project_editor = null;
project_editor = projectmanager.getCurrentProject();
if (project_editor != null)
return project_editor.getLocation();
return "";
}
public static WorkContext getWorkContext () {
return _workcontext;
}
/**
* Retrives the current working directory location (i.e. to save failes etc.)
*/
public static String getCurrentOpenDir () {
return current_open_dir;
}
/**
* Sets the current working directory location
*/
public static void setCurrentOpenDir (String dir) {
current_open_dir = dir;
}
/**
* Retrives the current working directory location (i.e. to save failes etc.)
*/
public static String getCurrentStoreDir () {
return current_store_dir;
}
/**
* Sets the current working directory location
*/
public static void setCurrentStoreDir (String dir) {
current_store_dir = dir;
}
/**
*
* Finalises the tool. Saves configuration data.
*
*/
public void finish (){
// fileviewer.saveConfig();
storeSettings ();
saveRecentFiles ();
}
private void storeSettings () {
profileeditor.store();
transformationeditor.store();
ProjectEditor editor = projectmanager.getCurrentProject();
if (editor != null)
editor.saveProject();
}
/**
*
* Starts the UMT tool and initates some basics
*
*/
public static void main (String [] args){
try {
String umt_type = System.getProperty("umt.type");
final UMTMain app = new UMTMain(args, umt_type);
app.setSize (800,700);
app.setLocation (200,100);
app.setVisible (true);
app.addWindowListener (new WindowAdapter(){
public void windowClosing (WindowEvent we){
app.finish ();
System.exit(0);
}
});
} catch (Exception ex) {
}
}
/**
*
* Splash-screen shower class
*
*/
private class UmtSplash extends JFrame implements Runnable
{
public UmtSplash () {
super ("Loading UMT...");
setIconImage(appicon.getImage());
String vm = System.getProperty("java.vm.version");
if ((int)vm.charAt(0) >= 1 && (int)vm.charAt(3) >= 4) {
// Java 1.4
this.setUndecorated(true);
}
Thread t = new Thread (this);
t.start();
}
public void finish () {
setVisible(false);
}
public void run () {
getContentPane().setLayout (new BorderLayout ());
ImageIcon splash = null;
if (_umt_type == UMTMain.UMT_SYSTEM_FAMILY)
splash = new ImageIcon(family_img_dir + "splash.gif");
else
splash = new ImageIcon(img_dir + "splash.gif");
JLabel label = new JLabel (splash);
setSize (splash.getIconWidth(), splash.getIconHeight());
setLocation (320,300);
getContentPane().add (label);
// setUndecorated(true); // Does not work in JDK 1.3!!!
setVisible(true);
}
}
/**
* Transformation progress displayer...
*/
private class TransformationProgress extends JFrame implements Runnable
{
private volatile boolean in_progress = false;
private volatile int progress = 0;
public TransformationProgress (String title) {
super ("Transformation in progress - " + title);
in_progress = true;
setLocation (UMTMain.this.getX() + 120, UMTMain.this.getY() + 40);
setSize (200, 40);
setVisible (true);
Thread t = new Thread (this);
t.start();
}
public void setInProgress (boolean is_in_progress) {
in_progress = is_in_progress;
}
public synchronized void updateBar () {
}
public void paintComponents (Graphics g) {
super.paintComponents(g);
g.setColor(Color.blue.brighter());
g.fillRect(0,0, progress, 40);
}
public void run () {
// progress_bar = new JProgressBar(0, 120);
// progress_bar.setValue(0);
// progress_bar.setStringPainted(true);
while (in_progress) {
// if (progress_bar.getValue() >= progress_bar.getMaximum())
// progress_bar.setValue(4);
// else
// progress_bar.setValue(progress_bar.getValue() + 4);
try {
if (progress > 200)
progress = 0;
else
progress+=10;
invalidate ();
repaint ();
System.out.println (".");
Thread.sleep(100);
} catch (InterruptedException ex) {
}
}
setVisible (false);
}
}
/**
*
* Handles actions for transformations. Reads transformation properties
* and initiates the actions
*
*/
private class TransformationActionListener implements ActionListener /*, Runnable */
{
private volatile String action;
public void executeTransformation () {
output.clear();
// output.setColors(Color.black, Color.white);
output.addLine("Transformation in progress (" + new Date().toString() + ")");
pimviewer.setTransforming(true);
try{
fileviewer.clear ();
setLastTransformation (action);
PropertyGroup group = transformationeditor.getPropertyManager().getPropertyGroupForItem(action);
String type = group.getProperty("Type");
String outputtype = group.getProperty("Outputtype");
String implementation = FileUtils.replaceSeparator(group.getProperty("Implementation"));
String direction = group.getProperty("Direction");
String gendir = "src";
if (current_store_dir != null && !(current_store_dir.equals(""))){
gendir = current_store_dir + System.getProperty("file.separator") + gendir;
}
ProjectEditor current = null;
try {
current = projectmanager.getCurrentProject();
if (current != null) {
gendir = current.getGenDir ();
gendir = current.getLocation() + System.getProperty("file.separator") + gendir;
String userfile = current.getUserPropertiesFile();
PropertyGroup userprops = current.getUserProperties();
if (userfile != null && !userfile.equals("")) {
// Create the user parameters and store them to the file
// get directory from the location of the 'implementation'
File implfile = new File (implementation);
String dir = implfile.getParent();
if(dir != null) {
PrintWriter pf = null;
try {
File file = new File (dir + System.getProperty("file.separator") + userfile);
pf = new PrintWriter( new FileWriter (file));
pf.println("<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http:// www.w3.org/1999/XSL/Transform\">");
pf.println("\n\n<!-- Generated file for user properties.-->\n\n");
Map userproperties = userprops.getProperties();
Iterator names = userproperties.keySet().iterator();
while (names.hasNext()) {
String name = (String)names.next();
String[] value = (String[])userproperties.get(name);
pf.println(" <xsl:variable name=\"" + name + "\">" + value[0] + "</xsl:variable>");
}
pf.println("</xsl:stylesheet>");
pf.close();
} catch (Exception ex) {
System.out.println ("Error writing user parameters file: " + ex.getMessage());
ex.printStackTrace();
} finally {
pf.close ();
}
}
}
}
} catch (Exception ex) {
}
TransformerEngineFactory trefactory = new TransformerEngineFactory (output);
TransformerEngine tre = trefactory.createTransformer(type, outputtype, implementation, direction);
if (tre != null) {
// TODO : Generelisize through usage of interface.... 'IReverseTransformer'
if (tre instanceof DefaultReverseTransformer) {
tre.setOutputDir(gendir);
tre.addTransformationResultListener (new TransformationResultListener(){
public void notifyNewResult (Object result)
{
System.out.println ("Reverse transformation ....");
if (result instanceof String) {
tab.setForegroundAt(RESULT_TAB_INDEX, Color.red);
tab.setEnabledAt(RESULT_TAB_INDEX, true);
fileviewer.setTextOutput ((String)result, "Reverse transformation result");
pimviewer.openHutnReader((String)result);
}
}
public void notifyStarting ()
{}
public void notifyFinished ()
{}
});
tre.setTransformationImpl(implementation);
tre.doTransformation();
} else {
tre.setOutputDir(gendir);
tre.addTransformationResultListener (fileviewer);
tre.addTransformationResultListener (new TransformationResultListener(){
public void notifyNewResult (Object result)
{
tab.setForegroundAt(RESULT_TAB_INDEX, Color.red);
tab.setEnabledAt(RESULT_TAB_INDEX, true);
}
public void notifyStarting ()
{
// output.setColors(Color.black, Color.white);
}
public void notifyFinished ()
{
// output.setColors(Color.white, Color.black);
}
});
String buffer = pimviewer.getHutnBuffer ();
if (buffer == null || buffer.equalsIgnoreCase ("")){
// File inputfile = pimviewer.getHutnFile();
// if (inputfile == null) {
JOptionPane.showMessageDialog (UMTMain.this, "No model loaded.");
return;
}
// System.out.println (buffer);
if (_transformationcontext == null) {
tre.setInputSource (new StringReader(buffer));
} else {
XMLUtility xmlutil = new XMLUtility();
String nodename = _transformationcontext.getNodeName();
String nodeid = _transformationcontext.getAttribute("id");
Document owner = _transformationcontext.getOwnerDocument();
Element docel = owner.getDocumentElement();
StringWriter swriter = new StringWriter ();
XMLUtility.writeNode(_transformationcontext, swriter, 0);
String xmlbuffer = swriter.toString();
// System.out.println (xmlbuffer);
// tre.setInputSource(new StringReader(buffer));
tre.setContext (nodename, nodeid);
tre.setInputSource (new StringReader(xmlbuffer));
}
tre.setTransformationImpl (implementation);
tre.doTransformation ();
_workcontext.setState(WorkContext.STATE_PERFORMED_ACTION);
}
}
} catch (Exception ex){
ex.printStackTrace();
output.addLine ("UMTMain::TransformationActionListener::actionPerformed() - Could not perform transformation: " + action);
}
// output.setColors(Color.white, Color.black);
// output.setPosition (0);
pimviewer.setTransforming(false);
pimviewer.paintImmediately(pimviewer.getBounds());
UMTMain.this.validate();UMTMain.this.repaint();
}
public void actionPerformed (ActionEvent ae)
{
action = ae.getActionCommand();
executeTransformation ();
// TODO: Remove
// Thread t = new Thread (this);
// t.start();
}
}
/**
*
* Handles events for changing look and feel.
*
*/
private class LafChangeActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String action = ae.getActionCommand();
for (int i = 0; i < lafNames.length;i++)
{
if(action.equalsIgnoreCase(lafNames[i])) {
setLaf (lafClasses[i]);
return;
}
}
}
}
/**
*
* Sets a new Look and Feel
*
*/
private void setLaf (String lafclass)
{
try{
UIManager.setLookAndFeel(lafclass);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception ex){
// LAF NOT SUPPORTED
System.out.println ("LAF Change exception: " + ex.getMessage());
}
}
/**
*
*/
private class TabChangeListener implements ChangeListener
{
public void stateChanged (ChangeEvent ce) {
Object source = ce.getSource();
if (source == tab) {
tab.setForegroundAt(tab.getSelectedIndex(), Color.black);
}
}
}
/**
*
* Action listener for project-menu-related events
*
*/
public static boolean environmentIsEmbedded () {
return _runtime_environment == RUNTIME_EMBEDDED;
}
private class ProjectActionListener implements ActionListener
{
public void actionPerformed (ActionEvent ae) {
output.clear();
String action = ae.getActionCommand();
if (action.equalsIgnoreCase ("new")) {
projectmanager.saveProject();
projectmanager.createProjectDialog();
// projectmanager.selectProject ();
} else if (action.equalsIgnoreCase ("open")) {
projectmanager.saveProject();
projectmanager.selectProject("Open");
} else if (action.equalsIgnoreCase ("close")) {
projectmanager.saveProject();
projectmanager.closeProject ();
} else if (action.equalsIgnoreCase ("save")) {
projectmanager.saveProject();
} else if (action.equalsIgnoreCase("delete")){
projectmanager.selectProject("delete");
} else if (action.equalsIgnoreCase("delete_current")) {
String current = projectmanager.getCurrentProjectName();
String id = "";
ProjectEditor editor = projectmanager.getCurrentProject();
if (editor != null)
id = projectmanager.getCurrentProject().getId();
int result = JOptionPane.showConfirmDialog(UMTMain.this, "Sure you want to delete current project '" + current + "'");
if (result == JOptionPane.OK_OPTION) {
projectmanager.closeProject();
projectmanager.deleteProject(id);
}
} else if (action.equalsIgnoreCase ("Settings")) {
projectmanager.showCurrentProject();
}
}
}
/**
* Event listener to handle opening, closing and saving of projects
*/
private class ProjectEventListener implements ProjectListener
{
public void projectNew (String project, String location, String id) {
System.out.println ("ProjectEventListener::projectNew - " + project + " id=" + id);
projectmanager.doOpenProject(id);
setMenuEnabled (project_menuitems, true);
setMenuEnabled (model_menuitems, true);
}
public void projectOpened (String project, String location, String id) {
UMTMain.this.setTitle(title + " [" + project + "]");
try {
pimviewer.closeView();
ProjectEditor current = projectmanager.getCurrentProject();
if (current != null)
transformationeditor.addPropertyGroupEditorLister(current);
String[] sources = current.getSources();
// File sourcefile = new File (location + System.getProperty("file.separator") + source);
// For now, only open the first file....
for (int i = 0; i < sources.length; i++) {
File sourcefile = new File(sources[i]);
doOpenAnyFile (sourcefile, false, "class");
}
// TODO: ADD RECENT PROJECT....
_workcontext.setState(WorkContext.STATE_OPENED_PROJECT);
} catch (Exception ex) {
output.addLine("" + ex.getMessage());
}
setMenuEnabled (project_menuitems, true);
setMenuEnabled (model_menuitems, true);
tab.setEnabledAt(PROJECT_TAB_INDEX, true);
ProjectEditor peditor = projectmanager.getCurrentProject();
if (peditor != null)
tab.setComponentAt(PROJECT_TAB_INDEX, peditor.getProjectViewer());
}
public void projectClosed (String project, String id) {
UMTMain.this.setTitle(title + " (no project)");
pimviewer.closeView();
setMenuEnabled (project_menuitems, false);
setMenuEnabled (model_menuitems, false);
tab.setEnabledAt(PROJECT_TAB_INDEX, false);
_workcontext.setState(WorkContext.STATE_INITIAL);
}
public void projectSaved (String project, String location, String id) {
}
}
/**
* MenuListener to detect if the transformation menu is selected
*/
private class UmtMenuListener implements MenuListener
{
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
// System.out.println ("MainMenuListener::menuDeselected");
}
public void menuSelected(MenuEvent e) {
try {
JMenu menu = (JMenu)e.getSource();
if (menu == forward_transformationmenu || menu == reverse_transformationmenu) {
menu.removeAll();
if (menu == forward_transformationmenu)
setTransformationItemsForMenu (menu, null, "forward");
else
setTransformationItemsForMenu (menu, null, "reverse");
} else {
// menu == reverse transformation menu
}
} catch (Exception ex) {
}
}
}
/**
* Retrieves the names of available profiles
* @return Array of profile names
*/
public static String[] getProfileNames () {
return profileeditor.getProfileNames();
}
/**
* Sets the active profile
*/
public static void setActiveProfile (String profilename) {
profileeditor.setActiveProfile(profilename);
}
public static String[] getTransformationNames () {
return transformationeditor.getTransformationNames();
}
/**
*
* @param menu
* @param context
* @param trans_direction
*/
public void setTransformationItemsForMenu (JMenu menu, Element context, String trans_direction) {
_transformationcontext = context;
transformationActionListener = new TransformationActionListener ();
Iterator transformations = transformationeditor.getPropertyManager().getPropertyGroups();
for (;transformations.hasNext();){
PropertyGroup transformation = (PropertyGroup) transformations.next();
String direction = transformation.getProperty("Direction");
String profile = transformation.getProperty("Profile");
JMenuItem item = new JMenuItem (transformation.getName());
if (direction.equalsIgnoreCase("Forward") && trans_direction.equalsIgnoreCase("forward")){
menu.add (item);
item.addActionListener (transformationActionListener);
} else if (direction.equalsIgnoreCase("Reverse") && trans_direction.equalsIgnoreCase("reverse")){
menu.add (item);
item.addActionListener (transformationActionListener);
}
}
}
/**
* Implementation of UriViewerListener interface
* @param event
*/
public void viewerEvent (String event) {
if (event.startsWith("umt:menu")) {
String menu = event.substring(9);
int submenuindex = menu.indexOf(":");
String submenu = null;
if (submenuindex > -1) {
submenu = menu.substring(submenuindex + 1);
menu = menu.substring(0, submenuindex);
}
JMenuBar menubar = this.getJMenuBar();
JMenuItem clickitem = null;
for (int i = 0; i < menubar.getMenuCount(); i++) {
JMenuItem m = menubar.getMenu(i), item = null;
if (m != null && menu.equalsIgnoreCase(m.getText())) {
// This is the right top level menu
clickitem = m;
m.doClick();
menu = submenu;
JMenuItem leitem = null;
while (menu != null && m instanceof JMenu) {
submenuindex = submenu.indexOf(":");
if (submenuindex > -1) {
submenu = menu.substring(submenuindex + 1);
menu = menu.substring(0, submenuindex);
for (int j = 0; j < ((JMenu)m).getMenuComponentCount(); j++){
leitem = (JMenuItem) ((JMenu)m).getMenuComponent(j);
if (menu.equalsIgnoreCase(leitem.getText())){
leitem.doClick();
break;
}
}
} else {
// Look for the menu item to invoke at this level
for (int j = 0; j < ((JMenu)m).getMenuComponentCount(); j++){
leitem = (JMenuItem) ((JMenu)m).getMenuComponent(j);
if (menu.equalsIgnoreCase(leitem.getText())) {
leitem.doClick();
break;
}
}
}
m = leitem;
menu = submenu;
}
break;
}
}
/*
if (clickitem != null)
clickitem.doClick();
*/
}
}
/**
* Implementation of ResourceLoadListener interface
*
* Just closes openned resources; Must be handled after the reader thread has finished;
* Event method is called from "PIMViewer" reader thread.
*/
public void resourceLoaded (String description, String resource) {
if (_modelreader != null){
try {
_modelreader.close();
_modelreader = null;
} catch (IOException ioex) {
System.out.println ("UMTMain::resourceLoaded:" + ioex);
}
}
if (_zipfile != null) {
try {
_zipfile.close();
} catch (IOException zipex) {
System.out.println ("UMTMain::resourceLoaded:" + zipex);
}
}
}
} // End Class UMTMain