GrxProjectItem.java
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2008, AIST, the University of Tokyo and General Robotix Inc.
3  * All rights reserved. This program is made available under the terms of the
4  * Eclipse Public License v1.0 which accompanies this distribution, and is
5  * available at http://www.eclipse.org/legal/epl-v10.html
6  * Contributors:
7  * General Robotix Inc.
8  * National Institute of Advanced Industrial Science and Technology (AIST)
9  */
10 /*
11  * GrxProjectItem.java
12  *
13  * Copyright (C) 2007 GeneralRobotix, Inc.
14  * All Rights Reserved
15  *
16  * @author Yuichiro Kawasumi (General Robotix, Inc.)
17  */
18 
19 package com.generalrobotix.ui.item;
20 
21 import java.io.*;
22 import java.lang.reflect.InvocationTargetException;
23 import java.net.URL;
24 import java.util.*;
25 
26 import javax.xml.parsers.DocumentBuilder;
27 import javax.xml.parsers.DocumentBuilderFactory;
28 import javax.xml.parsers.ParserConfigurationException;
29 import javax.xml.transform.OutputKeys;
30 import javax.xml.transform.Transformer;
31 import javax.xml.transform.TransformerConfigurationException;
32 import javax.xml.transform.TransformerException;
33 import javax.xml.transform.TransformerFactory;
34 import javax.xml.transform.dom.DOMSource;
35 import javax.xml.transform.stream.StreamResult;
36 
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.jface.action.Action;
39 import org.eclipse.jface.dialogs.InputDialog;
40 import org.eclipse.jface.dialogs.MessageDialog;
41 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
42 import org.eclipse.jface.operation.IRunnableWithProgress;
43 import org.eclipse.jface.preference.IPreferenceStore;
44 import org.eclipse.osgi.util.NLS;
45 import org.eclipse.swt.SWT;
46 import org.eclipse.swt.widgets.FileDialog;
47 import org.eclipse.ui.IPerspectiveDescriptor;
48 import org.eclipse.ui.IPerspectiveRegistry;
49 import org.eclipse.ui.IWorkbench;
50 import org.eclipse.ui.IWorkbenchPage;
51 import org.eclipse.ui.IWorkbenchWindow;
52 import org.eclipse.ui.PlatformUI;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
55 import org.w3c.dom.Node;
56 import org.w3c.dom.NodeList;
57 import org.xml.sax.InputSource;
58 import org.xml.sax.SAXException;
59 
63 import com.generalrobotix.ui.*;
72 
73 @SuppressWarnings({ "unchecked", "serial" }) //$NON-NLS-1$ //$NON-NLS-2$
74 public class GrxProjectItem extends GrxBaseItem {
75  public static final String TITLE = "Project"; //$NON-NLS-1$
76  public static final String DEFAULT_DIR = "/"; //$NON-NLS-1$
77  public static final String FILE_EXTENSION = "xml"; //$NON-NLS-1$
78 
79  public static final int MENU_CREATE=0, MENU_RESTORE=1, MENU_LOAD=2, MENU_SAVE=3, MENU_SAVE_AS=4, MENU_IMPORT=5;
80  private Vector<Action> menu_;
81 
82  private static final String MODE_TAG = "mode"; //$NON-NLS-1$
83  private static final String WINCONF_TAG = "perspective"; //$NON-NLS-1$
84 
85  private Document doc_;
86  private DocumentBuilder builder_;
87  private Transformer transformer_;
88  private HashMap<String, Properties> viewProperties_ = new HashMap<String, Properties>();
89 
90  private Map<String, ModeNodeInfo> modeInfoMap_ = new HashMap<String, ModeNodeInfo>();
91 
92  private class ModeNodeInfo {
93  Element root;
94  List propList;
95  NodeList itemList;
96  NodeList viewList;
97  Element windowConfig;
98  }
99 
100  public GrxProjectItem(String name, GrxPluginManager manager) {
101  super(name, manager);
102 // setIcon(manager_.ROBOT_ICON);
103  DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
104  TransformerFactory tffactory = TransformerFactory.newInstance();
105 
106  try {
107  builder_ = dbfactory.newDocumentBuilder();
108  transformer_ = tffactory.newTransformer();
109  transformer_.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
110  transformer_.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
111  setDefaultDirectory();
112  } catch (ParserConfigurationException e) {
113  e.printStackTrace();
114  } catch (TransformerConfigurationException e) {
115  e.printStackTrace();
116  }
117  }
118 
119  public boolean create() {
120  viewProperties_.clear();
121  clear();
122  setURL("");
123  for (int i=0; ; i++) {
124  File f = new File(getDefaultDir().getAbsolutePath()+"/"+"newproject"+i+".xml"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
125  if (!f.isFile()) {
126  setName(f.getName().split("[.]")[0]); //$NON-NLS-1$
127  break;
128  }
129  }
130 
131  doc_ = builder_.newDocument();
132  element_ = doc_.createElement("grxui"); //$NON-NLS-1$
133  element_.appendChild(doc_.createTextNode("\n")); //$NON-NLS-1$
134  doc_.appendChild(element_);
135  _updateModeInfo();
136  IWorkbenchPage page=null;
137  IWorkbench workbench = PlatformUI.getWorkbench();
138  if( workbench != null){
139  IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
140  for(IWorkbenchWindow window : windows){
141  page = window.getActivePage();
142  if (page != null &&
143  page.getPerspective().getId().equals(GrxUIPerspectiveFactory.ID+ ".project") )
144  page.closePerspective(page.getPerspective(), false, false);
145  }
146  }
147 
148  List<GrxBaseView> vl = manager_.getViewList();
149  for (int i=0; i<vl.size(); i++)
150  if (vl.get(i) != null) vl.get(i).restoreProperties();
151 
152  return true;
153  }
154 
155  private void _updateModeInfo() {
156  modeInfoMap_.clear();
157 
158  NodeList modeList = doc_.getElementsByTagName(MODE_TAG);
159  for (int i=0; i<modeList.getLength(); i++) {
160  ModeNodeInfo mi = new ModeNodeInfo();
161  mi.root = (Element)modeList.item(i);
162  modeInfoMap_.put(mi.root.getAttribute("name"), mi); //$NON-NLS-1$
163 
164  // property node
165  NodeList propList = mi.root.getElementsByTagName(PROPERTY_TAG);
166  List<Element> elList = new ArrayList<Element>();
167  for (int j=0; j<propList.getLength(); j++) {
168  if (propList.item(j).getParentNode() == mi.root)
169  elList.add((Element)propList.item(j));
170  }
171  mi.propList = elList;
172 
173  // item node
174  mi.itemList = mi.root.getElementsByTagName(ITEM_TAG);
175 
176  // view node
177  mi.viewList = mi.root.getElementsByTagName(VIEW_TAG);
178 
179  // window config element
180  NodeList wconfList = mi.root.getElementsByTagName(WINCONF_TAG);
181  if (wconfList.getLength() > 0)
182  mi.windowConfig = (Element)wconfList.item(0);
183  else
184  mi.windowConfig = null;
185 
186  }
187  }
188 
189  private ModeNodeInfo _getModeNodeInfo(String mode) {
190  ModeNodeInfo mi = modeInfoMap_.get(mode);
191  if (mi == null) {
192  mi = new ModeNodeInfo();
193 
194  NodeList nodeList = doc_.getElementsByTagName(MODE_TAG);
195  for (int i=0; i<nodeList.getLength(); i++) {
196  Element e = (Element)nodeList.item(i);
197  if (e.getAttribute("name").equals(mode)) { //$NON-NLS-1$
198  mi.root = e;
199  break;
200  }
201  }
202  if (mi.root == null) {
203  mi.root = doc_.createElement(MODE_TAG);
204  mi.root.setAttribute("name", mode); //$NON-NLS-1$
205  element_.appendChild(doc_.createTextNode(INDENT4));
206  element_.appendChild(mi.root);
207  element_.appendChild(doc_.createTextNode("\n")); //$NON-NLS-1$
208  }
209 
210  _updateModeInfo();
211  }
212 
213  return mi;
214  }
215 
216  public void setWindowConfigElement(String mode, Element element){
217  _getModeNodeInfo(mode).windowConfig = element;
218  }
219 
220  public Element getWindowConfigElement(String mode) {
221  return _getModeNodeInfo(mode).windowConfig;
222  }
223 
224  private void storeMode(String mode) {
225  Element modeEl = _getModeNodeInfo(mode).root;
226  NodeList list = modeEl.getChildNodes();
227  for (int i=list.getLength()-1; i>=0; i--)
228  modeEl.removeChild(list.item(i));
229 
230  modeEl.appendChild(doc_.createTextNode("\n")); //$NON-NLS-1$
231 
232  List<GrxBaseItem> itemList = manager_.getActiveItemList();
233  for (int i=0; i<itemList.size(); i++) {
234  GrxBaseItem item = itemList.get(i);
235  modeEl.appendChild(doc_.createTextNode(INDENT4+INDENT4));
236  item.setDocument(doc_);
237  modeEl.appendChild(item.storeProperties());
238  modeEl.appendChild(doc_.createTextNode("\n")); //$NON-NLS-1$
239  }
240 
241  List<GrxBaseView> viewList = manager_.getActiveViewList();
242  for (int i=0; i<viewList.size(); i++) {
243  GrxBaseView view = viewList.get(i);
244  if (view.propertyNames().hasMoreElements()) {
245  view.setDocument(doc_);
246  Element element = view.storeProperties();
247  if(element!=null){
248  modeEl.appendChild(doc_.createTextNode(INDENT4+INDENT4));
249  modeEl.appendChild(element);
250  modeEl.appendChild(doc_.createTextNode("\n")); //$NON-NLS-1$
251  }
252  }
253  }
254 
255  modeEl.appendChild(doc_.createTextNode(INDENT4));
256  }
257 
258  @SuppressWarnings("deprecation")
259  private Element storePerspectiveConf(Element element){
260  IWorkbenchPage page=null;
261  IWorkbench workbench = PlatformUI.getWorkbench();
262  if( workbench != null){
263  IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
264  if (window != null){
265  page = window.getActivePage();
266  if (!page.getPerspective().getId().contains(GrxUIPerspectiveFactory.ID) ){
267  return null;
268  }
269  }
270  }
271 
272  IPerspectiveRegistry perspectiveRegistry=workbench.getPerspectiveRegistry();
273  IPerspectiveDescriptor orgPd=perspectiveRegistry.findPerspectiveWithId(GrxUIPerspectiveFactory.ID );
274  IPerspectiveDescriptor tempPd=perspectiveRegistry.findPerspectiveWithId(GrxUIPerspectiveFactory.ID + ".project");
275  if(tempPd!=null)
276  perspectiveRegistry.deletePerspective(tempPd);
277  tempPd = perspectiveRegistry.clonePerspective(GrxUIPerspectiveFactory.ID + ".project", getName(), orgPd);
278  page.savePerspectiveAs(tempPd);
279  page.setPerspective(orgPd);
280  page.setPerspective(tempPd);
281  IPreferenceStore store = workbench.getPreferenceStore();
282  String confString=store.getString(GrxUIPerspectiveFactory.ID +".project"+"_persp");
283  Document doc=null;
284  try {
285  doc = builder_.parse(new InputSource(new StringReader(confString)));
286  Element confElement =doc.getDocumentElement();
287  Node elementCopy = doc_.importNode(confElement, true);
288  element.appendChild(elementCopy);
289  return (Element) elementCopy;
290  } catch (SAXException e1) {
291  e1.printStackTrace();
292  } catch (IOException e1) {
293  e1.printStackTrace();
294  }
295  return null;
296  }
297 
298  public Vector<Action> getMenu() {
299 
300  if( menu_ == null ){
301  menu_ = new Vector<Action>();
302 
303  // MENU_CREATE=0
304  menu_.add( new Action(){
305  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.CreateProject"); } //$NON-NLS-1$
306  public void run(){
307  boolean ans = MessageDialog.openConfirm( null, MessageBundle.get("GrxProjectItem.dialog.title.createProject"), MessageBundle.get("GrxProjectItem.dialog.message.createProject") ); //$NON-NLS-1$ //$NON-NLS-2$
308  if ( ans ){
309  if(!checkModifiedModel())
310  return;
311  manager_.refuseItemChange();
312  manager_.removeAllItems();
313  manager_.acceptItemChange();
314  }else if ( ans == false )
315  return;
316  create();
317  }
318  } );
319  // MENU_RESTORE=1
320  menu_.add( new Action(){
321  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.restoreProject"); } //$NON-NLS-1$
322  public void run(){
323  manager_.refuseItemChange();
324  manager_.removeAllItems();
325  restoreProject();
326  manager_.acceptItemChange();
327  }
328  } );
329  // MENU_LOAD=2
330  menu_.add( new Action(){
331  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.loadProject"); } //$NON-NLS-1$
332  public void run(){
333  if(!checkModifiedModel())
334  return;
335  load();
336  }
337  } );
338  // MENU_SAVE=3
339  menu_.add( new Action(){
340  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.saveProject"); } //$NON-NLS-1$
341  public void run(){
342  save();
343  }
344  } );
345  // MENU_SAVE_AS=4
346  menu_.add( new Action(){
347  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.saveProjectAs"); } //$NON-NLS-1$
348  public void run(){
349  saveAs();
350  }
351  } );
352  // MENU_IMPORT=3
353  /*
354  menu_.add( new Action(){
355  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.ImportISE"); } //$NON-NLS-1$
356  public void run(){
357  importISEProject();
358  }
359  } );
360  */
361  menu_.add( new Action(){
362  public String getText(){ return MessageBundle.get("GrxProjectItem.menu.addItem"); } //$NON-NLS-1$
363  public void run(){
364  addItem();
365  }
366  } );
367 
368  }
369 
370  return menu_;
371  }
372 
373  private boolean checkModifiedModel()
374  {
375  List<GrxModelItem> modelList = manager_.<GrxModelItem>getSelectedItemList(GrxModelItem.class);
376  List<GrxModelItem> modifiedModels = new ArrayList<GrxModelItem>();
377  for (int i=0; i<modelList.size(); i++) {
378  GrxModelItem model = modelList.get(i);
379  int ret=model.checkModifiedModel(false);
380  if(ret==GrxModelItem.MODIFIED_NG){
381  for(GrxModelItem modifiedModel : modifiedModels){
382  modifiedModel.reload();
383  }
384  return false;
385  }else if(ret==GrxModelItem.MODIFIED_OK){
386  modifiedModels.add(model);
387  }
388  }
389  return true;
390  }
391 
392  public void save(File f) {
393  if (f.exists()) {
394  if (!f.isFile())
395  return;
396  }
397 
398  String mode = manager_.getCurrentModeName();
399  storeMode(mode);
400 
401  setName(f.getName().split("[.]")[0]); //$NON-NLS-1$
402  setURL(f.getAbsolutePath());
403 
404  if (MessageDialog.openQuestion(null, MessageBundle.get("GrxProjectItem.dialog.savewindow.title"),
405  MessageBundle.get("GrxProjectItem.dialog.savewindow.message"))) { //$NON-NLS-1$
406  Element element = _getModeNodeInfo(mode).root;
407  Element windowConfigElement = storePerspectiveConf(element);
408  setWindowConfigElement(mode, windowConfigElement);
409  }
410 
411  if (f == null)
412  f = new File(getDefaultDir().getAbsolutePath()+"/"+getName()+".xml"); //$NON-NLS-1$ //$NON-NLS-2$
413 
414  if (!f.getAbsolutePath().endsWith(".xml")) //$NON-NLS-1$
415  f = new File(f.getAbsolutePath()+".xml"); //$NON-NLS-1$
416 
417  try {
418  DOMSource src = new DOMSource();
419  src.setNode(doc_);
420  StreamResult target = new StreamResult();
421  target.setOutputStream(new FileOutputStream(f));
422  transformer_.transform(src, target);
423  return ;
424  } catch (TransformerConfigurationException e) {
425  e.printStackTrace();
426  } catch (FileNotFoundException e) {
427  e.printStackTrace();
428  } catch (TransformerException e) {
429  e.printStackTrace();
430  }
431  MessageDialog.openError(null, MessageBundle.get("GrxProjectItem.dialog.saveError.title"), MessageBundle.get("GrxProjectItem.dialog.saveError.message"));
432  }
433 
434  public void saveAs() {
435  String path = getURL(true);
436  if (path == null)
437  path = getDefaultDir().getAbsolutePath()+"/"+getName()+".xml"; //$NON-NLS-1$ //$NON-NLS-2$
438 
439  File initialFile = new File(path);
440 
441  FileDialog fdlg = new FileDialog( GrxUIPerspectiveFactory.getCurrentShell(), SWT.SAVE);
442  String[] exts = { "*.xml" }, extNames={"GrxUI Project"}; //$NON-NLS-1$ //$NON-NLS-2$
443  fdlg.setFilterExtensions( exts );
444  fdlg.setFilterNames( extNames );
445 
446  fdlg.setFilterPath( initialFile.getParent() );
447  fdlg.setFileName( initialFile.getName() );
448 
449  String fPath = fdlg.open();
450  if( fPath != null ) {
451  File f = new File(fPath);
452  if (f.exists() && f.isFile()){
453  boolean ans = MessageDialog.openConfirm( null, MessageBundle.get("GrxProjectItem.dialog.title.saveProject"), //$NON-NLS-1$
454  MessageBundle.get("GrxProjectItem.dialog.message.saveProject0")+f.getName()+MessageBundle.get("GrxProjectItem.dialog.message.saveProject1") + //$NON-NLS-1$ //$NON-NLS-2$
455  MessageBundle.get("GrxProjectItem.dialog.message.saveProject2") ); //$NON-NLS-1$
456  if (ans == false)
457  return;
458  }
459  System.setProperty("CURRENT_DIR", f.getParent());
460  save( f );
461  setDefaultDirectory(f.getParent());
462  }
463  }
464 
465  public void save(){
466  if (getURL(true) == null){
467  saveAs();
468  }else{
469  File f = new File(getURL(true));
470  if (f.exists()){
471  save(f);
472  }else{
473  saveAs();
474  }
475  }
476  }
477 
481  public void load() {
482  FileDialog fdlg = new FileDialog( GrxUIPerspectiveFactory.getCurrentShell(), SWT.OPEN);
483  String[] fe = { "*.xml" }; //$NON-NLS-1$
484  fdlg.setFilterExtensions( fe );
485  fdlg.setFilterPath(getDefaultDir().getAbsolutePath());
486 
487  String fPath = fdlg.open();
488  if( fPath != null ) {
489  File f = new File(fPath);
490  load(f);
491  }
492  }
493 
499  public boolean load(File f) {
500  System.out.println( "[ProjectItem]@load ProjectFile load "+ f.toString()); //$NON-NLS-1$
501 
502  if (f == null || !f.isFile())
503  return false;
504  GrxSimulationItem simItem = manager_.<GrxSimulationItem>getSelectedItem(GrxSimulationItem.class, null);
505  if(simItem!=null && simItem.isSimulating())
506  simItem.stopSimulation();
507 
508  manager_.refuseItemChange();
509  manager_.removeAllItems();
510  manager_.focusedItem(manager_.getProject());
511  setName(f.getName().split("[.]")[0]); //$NON-NLS-1$
512 
513  String dir = f.getParent();
514  if(dir != null)
515  System.setProperty("CURRENT_DIR", dir);
516 
517  try {
518  doc_ = builder_.parse(f);
519  element_ = doc_.getDocumentElement();
520  _updateModeInfo();
521  file_ = f;
522  setURL(f.getAbsolutePath());
523  } catch (Exception e) {
524  GrxDebugUtil.printErr("project load:",e); //$NON-NLS-1$
525  file_ = null;
526  return false;
527  }
528 
529  // register mode
530  OrderedHashMap modes=(OrderedHashMap)manager_.getItemMap(GrxModeInfoItem.class);
531  Iterator<GrxModeInfoItem> it = modes.values().iterator();
532  NodeList list = doc_.getElementsByTagName(MODE_TAG);
533  for (int i=0; i<list.getLength(); i++) {
534  Element modeEl = (Element) list.item(i);
535  String modeName = modeEl.getAttribute("name"); //$NON-NLS-1$
536  if (modeName == null)
537  continue;
538  boolean found=false;
539  while (it.hasNext()) {
540  GrxModeInfoItem mode = it.next();
541  if(modeName.equals(mode.getName())){
542  mode.setElement(modeEl);
543  found=true;
544  break;
545  }
546  }
547  if(!found){
548  GrxModeInfoItem item = (GrxModeInfoItem)manager_.createItem(GrxModeInfoItem.class, modeName);
549  if (item != null) {
550  item.setElement(modeEl);
551  if (GrxXmlUtil.getBoolean(modeEl, "select", true)) { //$NON-NLS-1$
552  manager_.setSelectedItem(item, true);
553  }
554  }
555  manager_.setCurrentMode(item);
556  }
557  }
558 
559  setDefaultDirectory(f.getParent());
560  restoreProject();
561  manager_.acceptItemChange();
562  return true;
563  }
564 
565  public void restoreProject() {
566 
567  String mode = manager_.getCurrentModeName();
568  System.out.println("Restore Project (Mode:" +mode+")"); //$NON-NLS-1$ //$NON-NLS-2$
569 
570  IRunnableWithProgress runnableProgress = new IRunnableWithProgress() {
571  public void run(IProgressMonitor monitor) throws InterruptedException {
572  String mode = manager_.getCurrentModeName();
573  monitor.beginTask("Restore Project (Mode:" +mode+")", 10 ); //$NON-NLS-1$ //$NON-NLS-2$
574  restoreProject_work(mode, monitor);
575  monitor.done();
576  }
577  };
578  ProgressMonitorDialog progressMonitorDlg = new ProgressMonitorDialog(GrxUIPerspectiveFactory.getCurrentShell());
579  try {
580  progressMonitorDlg.run(false,false, runnableProgress);
581  //ダイアログの影が残ってしまぁE策  //
582  Grx3DView view3d = (Grx3DView)manager_.getView( Grx3DView.class, true );
583  if(view3d!=null){
584  view3d.repaint();
585  }
586  } catch (InvocationTargetException e) {
587  e.printStackTrace();
588  } catch (InterruptedException e) {
589  e.printStackTrace();
590  }
591  }
592 
593  private void restoreProject_work(String mode, IProgressMonitor monitor) {
594  //manager_.restoreProcess();
595 
596  monitor.worked(1);
597 
598  if (file_ == null || !file_.isFile())
599  {
600  return;
601  }
602  ModeNodeInfo minfo = modeInfoMap_.get(mode);
603 
604  monitor.worked(1);
605 
606  List propList = minfo.propList;
607  if (propList != null) {
608  for (int i=0; i<propList.size(); i++) {
609  Element propEl = (Element)propList.get(i);
610  String key = propEl.getAttribute("name"); //$NON-NLS-1$
611  String val = propEl.getAttribute("value"); //$NON-NLS-1$
612  setProperty(key, val);
613  }
614  }
615 
616  monitor.worked(1);
617 
618  if (minfo.itemList != null) {
619 
620  // 古ぁEEロジェクトファイルに対応  //
621  // ModeがSimulationでSimulationItemがなぁE合E自動的に作Eし、WorldStateItemのプロパティをSimulationItemに設定  //
622  if(mode.equals("Simulation") && !containSimulationItem(minfo.itemList)){
623  Element simElement = doc_.createElement(ITEM_TAG);
624  simElement.setAttribute("class", PreferenceConstants.SIMULATIONITEM);
625  simElement.setAttribute("name", "simulationItem");
626  simElement.setAttribute("select", "true");
627  minfo.root.appendChild(simElement);
628  minfo.itemList = minfo.root.getElementsByTagName(ITEM_TAG);
629  for (int i=0; i<minfo.itemList.getLength(); i++) {
630  Element itemElement = (Element)minfo.itemList.item(i);
631  if(itemElement.getAttribute("class").equals(PreferenceConstants.WORLDSTATEITEM)){
632  NodeList props = itemElement.getElementsByTagName(PROPERTY_TAG);
633  for (int j = 0; j < props.getLength(); ) {
634  Element propEl = (Element) props.item(j);
635  String key = propEl.getAttribute("name"); //$NON-NLS-1$
636  String val = propEl.getAttribute("value"); //$NON-NLS-1$
637  if(!key.equals("logTimeStep")){
638  Element element = doc_.createElement(PROPERTY_TAG);
639  element.setAttribute("name", key);
640  element.setAttribute("value", val);
641  simElement.appendChild(element);
642  itemElement.removeChild(propEl);
643  }else
644  j++;
645  }
646  }
647  }
648  }
649 
650  List<GrxBaseItem> il = new ArrayList<GrxBaseItem>();
651  for (int i = 0; i < minfo.itemList.getLength(); i++) {
652  GrxBaseItem p = (GrxBaseItem)_restorePlugin((Element) minfo.itemList.item(i));
653  if (p != null)
654  il.add(p);
655  }
656 
657  // for a item that is exclusive selection reselect
658  for (int i=0; i<il.size(); i++) {
659  GrxBaseItem item = il.get(i);
660  boolean select = GrxXmlUtil.getBoolean(item.getElement(), "select", false); //$NON-NLS-1$
661  //manager_.setSelectedItem(item, select);
662  }
663  }
664 
665  monitor.worked(1);
666 
667  if (minfo.windowConfig != null) {
668  Document doc = builder_.newDocument();
669  Node nodeCopy = doc.importNode(minfo.windowConfig, true);
670  doc.appendChild(nodeCopy);
671  StringWriter sw = new StringWriter();
672  try {
673  DOMSource src = new DOMSource();
674  src.setNode(doc);
675  StreamResult target = new StreamResult(sw);
676  transformer_.transform(src, target);
677  } catch (TransformerConfigurationException e) {
678  e.printStackTrace();
679  } catch (TransformerException e) {
680  e.printStackTrace();
681  }
682 
683  IWorkbenchPage page=null;
684  IWorkbench workbench = PlatformUI.getWorkbench();
685  if( workbench != null){
686  IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
687  if (window != null){
688  page = window.getActivePage();
689  if (!page.getPerspective().getId().contains(GrxUIPerspectiveFactory.ID) ){
690  return;
691  }
692  }
693  }
694  if (page!=null && page.getPerspective().getId().equals(GrxUIPerspectiveFactory.ID+ ".project") )
695  page.closePerspective(page.getPerspective(), false, false);
696  IPreferenceStore store = workbench.getPreferenceStore();
697  IPerspectiveRegistry perspectiveRegistry=workbench.getPerspectiveRegistry();
698  IPerspectiveDescriptor orgPd=perspectiveRegistry.findPerspectiveWithId(GrxUIPerspectiveFactory.ID );
699  IPerspectiveDescriptor tempPd=perspectiveRegistry.findPerspectiveWithId(GrxUIPerspectiveFactory.ID + ".project");
700  if(tempPd!=null)
701  perspectiveRegistry.deletePerspective(tempPd);
702  tempPd = perspectiveRegistry.clonePerspective(GrxUIPerspectiveFactory.ID + ".project", getName(), orgPd);
703  store.setValue(GrxUIPerspectiveFactory.ID + ".project"+"_persp", sw.toString());
704  if(page!=null)
705  page.setPerspective(tempPd);
706  }else{
707  IWorkbench workbench = PlatformUI.getWorkbench();
708  if( workbench != null){
709  IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
710  for(IWorkbenchWindow window : windows){
711  IWorkbenchPage page = window.getActivePage();
712  if (page != null &&
713  page.getPerspective().getId().equals(GrxUIPerspectiveFactory.ID+ ".project") )
714  page.closePerspective(page.getPerspective(), false, false);
715  }
716  }
717  }
718 
719  viewProperties_.clear();
720  if (minfo.viewList != null) {
721  for (int i = 0; i < minfo.viewList.getLength(); i++){
722  Element element = (Element)minfo.viewList.item(i);
723  NodeList props = element.getElementsByTagName(PROPERTY_TAG);
724  Properties properties = new Properties();
725  for (int j = 0; j < props.getLength(); j++) {
726  Element propEl = (Element) props.item(j);
727  String key = propEl.getAttribute("name"); //$NON-NLS-1$
728  String val = propEl.getAttribute("value"); //$NON-NLS-1$
729  properties.setProperty(key, val);
730  }
731  viewProperties_.put(element.getAttribute("name"), properties);
732  }
733  }
734 
735  List<GrxBaseView> vl = manager_.getViewList();
736  for (int i=0; i<vl.size(); i++)
737  if (vl.get(i) != null) vl.get(i).restoreProperties();
738 
739  }
740 
741  private GrxBasePlugin _restorePlugin(Element e) {
742  String iname = e.getAttribute("name"); //$NON-NLS-1$
743  if (iname == null || iname.length() == 0)
744  return null;
745  manager_.pluginLoader_.addURL(GrxXmlUtil.expandEnvVal(e.getAttribute("lib"))); //$NON-NLS-1$
746  Class cls = manager_.registerPlugin(e.getAttribute("class")); //$NON-NLS-1$
747  if (cls == null)
748  return null;
749  manager_.getMode().addItemClassList(cls);
750 
751  GrxBasePlugin plugin = null;
752  if (GrxBaseItem.class.isAssignableFrom(cls)) {
753  Class<? extends GrxBaseItem> icls = (Class<? extends GrxBaseItem>) cls;
754  String url = e.getAttribute("url"); //$NON-NLS-1$
755  if (!url.equals("")) //$NON-NLS-1$
756  plugin = manager_.loadItem(icls, iname, url);
757  else
758  plugin = manager_.createItem(icls, iname);
759  plugin = manager_.getItem(icls, iname);
760  }
761 
762  if (plugin != null) {
763  plugin.setElement(e);
764  plugin.restoreProperties();
765  if (GrxBaseItem.class.isAssignableFrom(cls)) {
766  manager_.itemChange((GrxBaseItem)plugin, GrxPluginManager.ADD_ITEM);
767  manager_.setSelectedItem((GrxBaseItem)plugin, true);
768  }
769  }
770 
771  return plugin;
772  }
773 
774  private boolean containSimulationItem(NodeList list){
775  for (int i = 0; i < list.getLength(); i++) {
776  if(((Element) list.item(i)).getAttribute("class").equals(PreferenceConstants.SIMULATIONITEM))
777  return true;
778  }
779  return false;
780  }
781 
782  private static final File DEFAULT_ISE_PROJECT_DIR = new File("../ISE/Projects"); //$NON-NLS-1$
783  public void importISEProject() {
784 
785  FileDialog fDialog = new FileDialog(null,SWT.SAVE);
786 
787  String [] exts = {"*.prj"}; //$NON-NLS-1$
788  String [] filterNames = {"ISE Project File(*.prj)"}; //$NON-NLS-1$
789  fDialog.setFilterExtensions(exts);
790  fDialog.setFilterNames(filterNames);
791  if( DEFAULT_ISE_PROJECT_DIR != null )
792  fDialog.setFilterPath( DEFAULT_ISE_PROJECT_DIR.getPath() );
793 
794  String openPath = fDialog.open();
795 
796  if( openPath != null ) {
797  //manager_.processingWindow_.setTitle("Importing ISE Project");
798  //manager_.processingWindow_.setMessage(" importing ISE Project ...");
799  //manager_.processingWindow_.setVisible(true);
800  //Thread t = new Thread() {
801  //public void run() {
802  //File f = fc.getSelectedFile();
803  File f = new File( openPath );
804  setName(f.getName().split(".prj")[0]); //$NON-NLS-1$
805  importISEProject(f);
806  //manager_.processingWindow_.setVisible(false);
807  //fc.setSelectedFile(null);
808  storeMode(manager_.getCurrentModeName());
809  //}
810  //};
811  //t.start();
812  }
813  }
814 
815  public Properties getViewProperties(String viewName){
816  return viewProperties_.get(viewName);
817  }
818 
819  private static String ENVIRONMENT_NODE = "jp.go.aist.hrp.simulator.EnvironmentNode"; //$NON-NLS-1$
820  private static String ROBOT_NODE = "jp.go.aist.hrp.simulator.RobotNode"; //$NON-NLS-1$
821  private static String COLLISIONPAIR_NODE = "jp.go.aist.hrp.simulator.CollisionPairNode"; //$NON-NLS-1$
822  private static String GRAPH_NODE = "jp.go.aist.hrp.simulator.GraphNode"; //$NON-NLS-1$
823 
824  private static String WORLD_STATE_ITEM = "com.generalrobotix.ui.item.GrxWorldStateItem"; //$NON-NLS-1$
825  private static String MODEL_ITEM = "com.generalrobotix.ui.item.GrxModelItem"; //$NON-NLS-1$
826  private static String COLLISIONPAIR_ITEM = "com.generalrobotix.ui.item.GrxCollisionPairItem"; //$NON-NLS-1$
827  private static String GRAPH_ITEM = "com.generalrobotix.ui.item.GrxGraphItem"; //$NON-NLS-1$
828 
829  public void importISEProject(File f) {
830  manager_.removeAllItems();
831 
833  try {
834  prop = new GrxConfigBundle(f.getAbsolutePath());
835  } catch (FileNotFoundException e) {
836  e.printStackTrace();
837  } catch (IOException e) {
838  e.printStackTrace();
839  }
840 
841  setProperty("nsHost", GrxCorbaUtil.nsHost()); //$NON-NLS-1$
842  Integer nsPort = new Integer(GrxCorbaUtil.nsPort());
843  setProperty("nsPort", nsPort.toString()); //$NON-NLS-1$
844 
845  String pname = prop.getStr("Project.name", ""); //$NON-NLS-1$ //$NON-NLS-2$
846  Class cls = manager_.registerPlugin(WORLD_STATE_ITEM);
847  GrxBaseItem newItem = manager_.createItem((Class <? extends GrxBaseItem>)cls, pname);
848  newItem.setDbl("totalTime", prop.getDbl("Project.totalTime", 20.0)); //$NON-NLS-1$ //$NON-NLS-2$
849  newItem.setDbl("timeStep", prop.getDbl("Project.timeStep", 0.001)); //$NON-NLS-1$ //$NON-NLS-2$
850  newItem.setDbl("logTimeStep", prop.getDbl("Project.timeStep", 0.001)); //$NON-NLS-1$ //$NON-NLS-2$
851  newItem.setProperty("method", prop.getStr("Project.method")); //$NON-NLS-1$ //$NON-NLS-2$
852  manager_.itemChange(newItem, GrxPluginManager.ADD_ITEM);
853  manager_.setSelectedItem(newItem, true);
854 
855  for (int i = 0; i < prop.getInt("Project.num_object", 0); i++) { //$NON-NLS-1$
856  String header = "Object" + i + "."; //$NON-NLS-1$ //$NON-NLS-2$
857  String oName = prop.getStr(header + "name"); //$NON-NLS-1$
858  String cName = prop.getStr(header + "class"); //$NON-NLS-1$
859  if (oName == null || cName == null)
860  continue;
861 
862  if (cName.equals(ENVIRONMENT_NODE) || cName.equals(ROBOT_NODE)) {
863  cls = manager_.registerPlugin(MODEL_ITEM);
864  try {
865  URL url = new URL(prop.getStr(header + "url")); //$NON-NLS-1$
866  newItem = manager_.loadItem((Class<? extends GrxBaseItem>)cls, oName, url.getPath());
867  if(newItem!=null){
868  manager_.itemChange(newItem, GrxPluginManager.ADD_ITEM);
869  manager_.setSelectedItem(newItem, true);
870  }
871  } catch (Exception e) {
872  e.printStackTrace();
873  }
874  if (newItem == null)
875  continue;
876 
877  if (cName.equals(ENVIRONMENT_NODE)) {
878  newItem.setProperty("isRobot", "false"); //$NON-NLS-1$ //$NON-NLS-2$
879  } else if (cName.equals(ROBOT_NODE)) {
880  newItem.setProperty("isRobot", "true"); //$NON-NLS-1$ //$NON-NLS-2$
881  Enumeration e = prop.keys();
882  while (e.hasMoreElements()) {
883  String key = (String)e.nextElement();
884  if (key.startsWith(header)) {
885  String newKey = key.substring(header.length());
886  if (key.endsWith(".angle")) { //$NON-NLS-1$
887  newItem.setDbl(newKey, prop.getDbl(key, 0.0));
888  } else if (key.endsWith(".mode")) { //$NON-NLS-1$
889  newItem.setProperty(newKey, prop.getStr(key, "Torque")); //$NON-NLS-1$
890  } else if (key.endsWith(".translation")) { //$NON-NLS-1$
891  newItem.setDblAry(newKey,
892  prop.getDblAry(key, new double[]{0.0, 0.0, 0.0}));
893  } else if (key.endsWith(".rotation")) { //$NON-NLS-1$
894  newItem.setDblAry(newKey,
895  prop.getDblAry(key, new double[]{0.0, 1.0, 0.0, 0.0}));
896  }
897  }
898  }
899 
900  String controller = prop.getStr(header + "controller"); //$NON-NLS-1$
901  controller = controller.replaceFirst("openhrp.", ""); //$NON-NLS-1$ //$NON-NLS-2$
902  double controlTime = prop.getDbl(header + "controlTime", 0.001); //$NON-NLS-1$
903  newItem.setProperty("controller", controller); //$NON-NLS-1$
904  newItem.setProperty("controlTime", String.valueOf(controlTime)); //$NON-NLS-1$
905 
906  String imageProcessor = prop.getStr(header + "imageProcessor"); //$NON-NLS-1$
907  if (imageProcessor != null) {
908  double imageProcessTime = prop.getDbl(header + "imageProcessTime", 0.001); //$NON-NLS-1$
909  newItem.setProperty("imageProcessor", imageProcessor); //$NON-NLS-1$
910  newItem.setProperty("imageProcessTime", String.valueOf(imageProcessTime)); //$NON-NLS-1$
911  }
912  }
913 
914  } else if (cName.equals(COLLISIONPAIR_NODE)) {
915  cls = manager_.registerPlugin(COLLISIONPAIR_ITEM);
916  newItem = manager_.createItem((Class<? extends GrxBaseItem>)cls, oName);
917  newItem.setProperty("objectName1", prop.getStr(header + "objectName1")); //$NON-NLS-1$ //$NON-NLS-2$
918  newItem.setProperty("jointName1", prop.getStr(header + "jointName1")); //$NON-NLS-1$ //$NON-NLS-2$
919  newItem.setProperty("objectName2", prop.getStr(header + "objectName2")); //$NON-NLS-1$ //$NON-NLS-2$
920  newItem.setProperty("jointName2", prop.getStr(header + "jointName2")); //$NON-NLS-1$ //$NON-NLS-2$
921  newItem.setProperty("slidingFriction", prop.getStr(header + "slidingFriction", "0.5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
922  newItem.setProperty("staticFriction", prop.getStr(header + "staticFriction", "0.5")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
923  newItem.setProperty("cullingThresh", prop.getStr(header + "cullingThresh", "0.01")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
924  newItem.setProperty("Restitution", prop.getStr(header + "Restitution", "0.0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
925  newItem.setProperty("sprintDamperModel", prop.getStr(header + "springDamplerModel", "false")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
926  newItem.setProperty("springConstant", prop.getStr(header + "springConstant", "0.0 0.0 0.0 0.0 0.0 0.0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
927  newItem.setProperty("damperConstant", prop.getStr(header + "damperConstant", "0.0 0.0 0.0 0.0 0.0 0.0")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
928 
929  } else if (cName.equals(GRAPH_NODE)) {
930  cls = manager_.registerPlugin(GRAPH_ITEM);
931  newItem = manager_.getItem((Class<? extends GrxBaseItem>)cls, null);
932  if (newItem == null)
933  newItem = manager_.createItem((Class<? extends GrxBaseItem>)cls, "GraphList1"); //$NON-NLS-1$
934  String items = prop.getStr(header + "dataItems"); //$NON-NLS-1$
935  newItem.setProperty(oName + ".dataItems", items); //$NON-NLS-1$
936  String[] str = items.split(","); //$NON-NLS-1$
937  String[] p = {
938  "object", "node", "attr", "index", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
939  "numSibling", "legend", "color" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
940  };
941  for (int j = 0; j < str.length; j++) {
942  for (int k = 0; k < p.length; k++) {
943  String key = str[j] + "." + p[k]; //$NON-NLS-1$
944  String value = prop.getStr(header + key);
945  if (value != null)
946  newItem.setProperty(oName + "." + key, value); //$NON-NLS-1$
947  }
948  }
949  }
950  newItem.restoreProperties();
951  manager_.setSelectedItem(newItem, true);
952  }
953  }
954 
955  //
956  private void setDefaultDirectory(){
957  String dir = Activator.getDefault().getPreferenceStore().getString("PROJECT_DIR"); //$NON-NLS-1$
958  if(dir.equals("")) //$NON-NLS-1$
959  dir = System.getenv("PROJECT_DIR"); //$NON-NLS-1$
960  if( dir != null ){
961  setDefaultDirectory( dir );
962  }
963  }
964 
965  private void addItem(){
966  TwoInputDialog dialog = new TwoInputDialog( null, MessageBundle.get("GrxProjectItem.dialog.addItem.title"), MessageBundle.get("GrxProjectItem.dialog.addItem.message0"),
967  "", null, MessageBundle.get("GrxProjectItem.dialog.addItem.message1"),"" );
968  if(dialog.open()==InputDialog.OK){
969  String[] values = dialog.getValues();
970  manager_.addPlugin(values[0], values[1]);
971  }
972  }
973 }
static final String get(String key)
final Integer getInt(String key, Integer defaultVal)
get integer value associated to key
void clear(CorbaSequence &seq)
final double[] getDblAry(String key, double[] defaultVal)
get double array associated to key
void restoreProject_work(String mode, IProgressMonitor monitor)
#define null
our own NULL pointer
Definition: IceTypes.h:57
Element storeProperties()
store properties
png_infop png_charpp name
Definition: png.h:2382
png_voidp int value
Definition: png.h:2113
RTC::ReturnCode_t ret(RTC::Local::ReturnCode_t r)
item corresponds to a robot model
static String nsHost()
get hostname where naming server is running
png_uint_32 i
Definition: png.h:2735
final void setDbl(String key, double value)
associate double value to key
void setWindowConfigElement(String mode, Element element)
void setDocument(Document doc)
set document
def j(str, encoding="cp932")
def run(tree, args)
int val
Definition: jpeglib.h:956
static String expandEnvVal(String str)
GrxProjectItem(String name, GrxPluginManager manager)
Object setProperty(String key, String value)
set property value associated with a keyword
boolean load(File f)
load a project file
path
prop
ModeNodeInfo _getModeNodeInfo(String mode)
final Double getDbl(String key, Double defaultVal)
get double value associated to key
final String getStr(String key)
get value associated to keyword
static int nsPort()
get port number where naming server is listening
プラグイン管理クラス GrxUIの核になるクラス。プラグインのロード等の、初期化を実行する。 プラグインとそ...
void setElement(Element element)
set element
def getText(self, nodes=None)
void restoreProperties()
restore properties. Called by menu item "restore Properties"
Properties getViewProperties(String viewName)
org
static BodyCustomizerHandle create(BodyHandle bodyHandle, const char *modelName)
final void setDblAry(String key, double[] value, int digits)
associate double array to key
static Boolean getBoolean(String[] path, String atr, boolean defaultValue)


openhrp3
Author(s): AIST, General Robotix Inc., Nakamura Lab of Dept. of Mechano Informatics at University of Tokyo
autogenerated on Sat May 8 2021 02:42:38