[openrtm-commit:00462] r496 - in trunk/OpenRTM-aist-Python: . OpenRTM_aist OpenRTM_aist/utils/rtc-template

openrtm @ openrtm.org openrtm @ openrtm.org
2011年 10月 19日 (水) 18:41:38 JST


Author: kurihara
Date: 2011-10-19 18:41:38 +0900 (Wed, 19 Oct 2011)
New Revision: 496

Added:
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_gen.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/profile_gen.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/yat.py
Removed:
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_src.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_gen.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_svc_impl.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/ezt.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/vcproject_gen.py
Modified:
   trunk/OpenRTM-aist-Python/
   trunk/OpenRTM-aist-Python/OpenRTM_aist/ManagerConfig.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/SystemLogger.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/gen_base.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/python_gen.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/rtc-template.py
   trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/uuid.py
   trunk/OpenRTM-aist-Python/setup.py
Log:
r495 merged. refs #2269



Property changes on: trunk/OpenRTM-aist-Python
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/RELENG_1_0/OpenRTM-aist-Python:345-404
/branches/RELENG_1_1/OpenRTM-aist-Python:396-478
   + /branches/RELENG_1_0/OpenRTM-aist-Python:345-404
/branches/RELENG_1_1/OpenRTM-aist-Python:396-478,495


Property changes on: trunk/OpenRTM-aist-Python/OpenRTM_aist/ManagerConfig.py
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/RELENG_1_0/OpenRTM-aist-Python/OpenRTM_aist/ManagerConfig.py:345-395
/branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/ManagerConfig.py:396-478
   + /branches/RELENG_1_0/OpenRTM-aist-Python/OpenRTM_aist/ManagerConfig.py:345-395
/branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/ManagerConfig.py:396-478,495


Property changes on: trunk/OpenRTM-aist-Python/OpenRTM_aist/SystemLogger.py
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/RELENG_1_0/OpenRTM-aist-Python/OpenRTM_aist/SystemLogger.py:345-395
/branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/SystemLogger.py:396-478
   + /branches/RELENG_1_0/OpenRTM-aist-Python/OpenRTM_aist/SystemLogger.py:345-395
/branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/SystemLogger.py:396-478,495

Copied: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_gen.py (from rev 495, branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_gen.py)
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_gen.py	                        (rev 0)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_gen.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -0,0 +1,245 @@
+#!/usr/bin/env python
+# -*- python -*-
+#
+#  @file README_src.py
+#  @brief rtc-template RTComponent's README file generator class
+#  @date $Date: 2007/01/11 07:47:03 $
+#  @author Noriaki Ando <n-ando at aist.go.jp>
+# 
+#  Copyright (C) 2004-2005
+#      Task-intelligence Research Group,
+#      Intelligent Systems Research Institute,
+#      National Institute of
+#          Advanced Industrial Science and Technology (AIST), Japan
+#      All rights reserved.
+# 
+#  $Id: README_gen.py 775 2008-07-28 16:14:45Z n-ando $
+#
+
+import os
+import time
+import gen_base
+
+readme = """#======================================================================
+#  RTComponent: [basicInfo.name] specificatioin
+#
+#  OpenRTM-aist-[version]
+#
+#  Date: [date] 
+#
+#  This file is generated by rtc-template with the following argments.
+#
+[for args in fmtd_args]
+#  [if-index args is first][else]  [endif]
+[args][if-index args is last][else]\\[endif]
+
+[endfor]
+#
+#======================================================================
+#    Basic Information
+#======================================================================
+# <rtc-template block="module">
+# </rtc-template>
+#======================================================================
+#    Activity definition
+#======================================================================
+# <rtc-template block="actions">
+# </rtc-template>
+#======================================================================
+#    InPorts definition
+#======================================================================
+# <rtc-template block="inport">
+# </rtc-template>
+#======================================================================
+#    OutPorts definition
+#======================================================================
+# <rtc-template block="outport">
+# </rtc-template>
+#======================================================================
+#    Service definition
+#======================================================================
+# <rtc-template block="service">
+# </rtc-template> 
+#======================================================================
+#    Configuration definition
+#======================================================================
+# <rtc-template block="configuration">
+# </rtc-template> 
+"""
+
+module = """Basic Information:
+  Description: [basicInfo.description]
+
+  Version:     [basicInfo.version]
+
+  Author:      [basicInfo.vendor]
+
+  Category:    [basicInfo.category]
+
+  Comp. Type:  [basicInfo.componentType]
+
+  Act. Type:   [basicInfo.activityType]
+
+  MAX Inst.:   [basicInfo.maxInstances]
+
+  Lang:        
+  Lang Type:   
+"""
+
+inport = """InPorts:
+[for inport in dataPorts]
+[if inport.portType is DataInPort]
+  Name:             [inport.name]
+
+  VarName:          [inport.rtcExt::varname]
+
+  PortNumber:       [inport.rtcDoc::doc.number]
+
+  Description:      [inport.rtcDoc::doc.description]
+
+  Type:             [inport.type]
+
+  InterfaceType:    [inport.interfaceType]
+
+  DataflowType:     [inport.dataflowType]
+
+  SubscriptionType: [inport.subscriptionType]
+
+  MaxOut: 
+
+[endif]
+[endfor]
+"""
+
+outport = """OutPorts:
+[for outport in dataPorts]
+[if outport.portType is DataOutPort]
+  Name:             [outport.name]
+
+  VarName:          [outport.rtcExt::varname]
+
+  PortNumber:       [outport.rtcDoc::doc.number]
+
+  Description:      [outport.rtcDoc::doc.description]
+
+  Type:             [outport.type]
+
+  InterfaceType:    [outport.interfaceType]
+
+  DataflowType:     [outport.dataflowType]
+
+  SubscriptionType: [outport.subscriptionType]
+
+  MaxOut: 
+
+[endif]
+[endfor]
+"""
+service = """ServicePorts:
+[for service in servicePorts]
+  PortName:    [service.name]
+
+  Description: [service.rtcDoc::doc.description]
+
+  InterfaceDescription: [service.rtcDoc::doc.ifdescription]
+
+  Position:    [service.rtcExt::position]
+
+  Interfaces:
+[for svcif in service.serviceInterface]
+    Name:         [svcif.name]
+
+    Description:  [svcif.rtcDoc::doc.description]
+
+    Type:         [svcif.type]
+
+    Direction:    [svcif.direction]
+
+    InstanceName: [svcif.instanceName]
+
+    IDLfile:      [svcif.idlFile]
+
+    FilePath:     [svcif.path]
+    
+[endfor]
+
+[endfor]
+
+"""
+
+configuration = """Configuration:
+[for config in configurationSet.configuration]
+  Name:         [config.name]
+
+  Description:  [config.rtcDoc::doc.description]
+
+  Type:         [config.type]
+
+  DefaultValue: [config.defaultValue]
+
+  Range:        [config.rtcDoc::doc.range]
+
+  Unit:         [config.rtcDoc::doc.unit]
+
+  Constraint:   [config.rtcDoc::doc.constraint]
+
+
+[endfor]"""
+
+class README_gen(gen_base.gen_base):
+	def __init__(self, data):
+		self.data = data.copy()
+		self.data['fname'] = "README." + self.data['basicInfo']['name']
+		self.data['version'] = os.popen("rtm-config --version", "r").read()
+		self.data['date'] = time.asctime()
+		
+		self.tags = {}
+		self.tags["module"] = module
+		self.tags["actions"] = self.CreateActions()
+		self.tags["inport"] = inport
+		self.tags["outport"] = outport
+		self.tags["service"] = service
+		self.tags["configuration"] = configuration
+		self.gen_tags(self.tags)
+		return
+
+	def CreateActions(self):
+		actnames = [
+			"onInitialize",
+			"onFinalize",
+			"onActivated",
+			"onDeactivated",
+			"onAborting",
+			"onError",
+			"onReset",
+			"onExecute",
+			"onStateUpdate",
+			"onShutdown",
+			"onStartup",
+			"onRateChanged",
+			]
+		acttext = """  %s:
+    Description:
+      [actions.%s.rtcDoc::doc.description]
+  
+    PreCondition:
+      [actions.%s.rtcDoc::doc.preCondition]
+  
+    PostCondition:
+      [actions.%s.rtcDoc::doc.postCondition]
+
+
+"""
+		actions = """Actions:
+"""
+		for a in actnames:
+			actions += acttext % (a,a,a,a)
+		return actions
+
+	def print_readme(self):
+		self.gen(self.data["fname"], readme, self.data, self.tags)
+
+	def print_all(self):
+		self.print_readme()
+
+

Deleted: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_src.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_src.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/README_src.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,199 +0,0 @@
-#!/usr/bin/env python
-# -*- python -*-
-#
-#  @file README_src.py
-#  @brief rtc-template RTComponent's README file generator class
-#  @date $Date: 2007/01/11 07:47:03 $
-#  @author Noriaki Ando <n-ando at aist.go.jp>
-# 
-#  Copyright (C) 2004-2005
-#      Task-intelligence Research Group,
-#      Intelligent Systems Research Institute,
-#      National Institute of
-#          Advanced Industrial Science and Technology (AIST), Japan
-#      All rights reserved.
-# 
-#  $Id: README_src.py,v 1.5 2007/01/11 07:47:03 n-ando Exp $
-#
-
-#
-#  $Log: README_src.py,v $
-#  Revision 1.5  2007/01/11 07:47:03  n-ando
-#  Some trivial fixes.
-#
-#  Revision 1.4  2005/09/08 09:23:36  n-ando
-#  - A bug fix for merge function.
-#
-#  Revision 1.3  2005/09/06 14:36:53  n-ando
-#  rtc-template's command options and data structure for ezt (Easy Template)
-#  are changed for RTComponent's service features.
-#  Now rtc-template can generate services' skeletons, stubs and
-#  implementation files.
-#  The implementation code generation uses omniidl's IDL parser.
-#
-#  Revision 1.2  2005/08/26 12:01:15  n-ando
-#  Now rtc-template uses ezt (Easy Template).
-#
-#  Revision 1.1.1.1  2005/05/12 09:06:18  n-ando
-#  Public release.
-#
-#
-
-import re
-import os
-import time
-import ezt
-import gen_base
-
-readme = """======================================================================
-  RTComponent: [module.name] specificatioin
-
-  OpenRTM-[version]
-  Date: [date]
-
-  This file is generated by rtc-template with the following argments.
-
-[for fmtd_args]    [fmtd_args]
-[end]
-======================================================================
-# <rtc-template block="module">
-# </rtc-template>
-
-
-======================================================================
-    Activity definition
-======================================================================
-
-[b]Initializing[e]
-
-[b]Ready[e]
-	[b]Entry[e]
-	[b]Do[e]
-	[b]Exit[e]
-
-[b]Starting[e]
-
-[b]Active[e]
-	[b]Entry[e]
-	[b]Do[e]
-	[b]Exit[e]
-
-[b]Stopping[e]
-
-[b]Error[e]
-	[b]Entry[e]
-	[b]Do[e]
-	[b]Exit[e]
-
-
-[b]Fatal Error[e]
-	[b]Entry[e]
-	[b]Do[e]
-	[b]Exit[e]
-
-[b]Exiting[e]
-
-======================================================================
-    InPorts definition
-======================================================================
-# <rtc-template block="inport">
-# </rtc-template>
-
-======================================================================
-    OutPorts definition
-======================================================================
-# <rtc-template block="outport">
-# </rtc-template>
-
-
-======================================================================
-    Service definition
-======================================================================
-# <rtc-template block="service">
-# </rtc-template> 
-
-======================================================================
-    Configuration definition
-======================================================================
-This area is reserved for future OpenRTM.
-
-"""
-
-module = """Description: [module.desc]
-Version:     [module.version]
-Author:      [module.vendor]
-Category:    [module.category]
-Comp. Type:  [module.comp_type]
-Act. Type:   [module.act_type]
-MAX Inst.:   [module.max_inst]
-Lang:        
-Lang Type:   
-"""
-
-inport = """[for inport]
-	Name:        [inport.name]
-	PortNumber:  [inport.num]
-	Description:
-	PortType: 
-	DataType:    [inport.type]
-	MaxOut: 
-	[b]Data Elements[e]
-		Number:
-		Name:
-		Type:
-		Unit:
-		RangeLow:
-		RangeHigh:
-		DefaultValue:
-[end]
-"""
-
-outport = """[for outport]
-	Name:        [outport.name]
-	PortNumber:  [outport.num]
-	Description:
-	PortType: 
-	DataType:    [outport.type]
-	MaxOut: 
-	[b]Data Elements[e]
-		Number:
-		Name:
-		Type:
-		Unit:
-		RangeLow:
-		RangeHigh:
-		DefaultValue:
-[end]
-"""
-service = """[for service]
-	Interface:   [service.type] 
-	Name:        [service.name]
-	Type:        [service.type]
-[end]
-"""
-
-class README_src(gen_base.gen_base):
-	def __init__(self, data):
-		self.data = data.copy()
-		self.data['fname'] = "README." + self.data['fname']
-		#self.data['version'] = os.popen("rtm-config --version", "r").read()
-		self.data['version'] = "0.4.1"
-		self.data['date'] = time.asctime()
-		self.data['b'] = "["
-		self.data['e'] = "]"
-
-		self.tags = {}
-		self.tags["module"] = module
-		self.tags["inport"] = inport
-		self.tags["outport"] = outport
-		self.tags["service"] = service
-
-		self.gen_tags(self.tags)
-		return
-
-	def print_readme(self):
-		self.gen(self.data["fname"], readme, self.data, self.tags)
-
-	def print_all(self):
-		self.print_readme()
-	

Deleted: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_gen.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_gen.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_gen.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,910 +0,0 @@
-#!/usr/bin/env python
-# -*- python -*-
-#
-#  @file cxx_gen.py
-#  @brief rtc-template C++ source code generator class
-#  @date $Date: 2007/07/20 17:28:56 $
-#  @author Noriaki Ando <n-ando at aist.go.jp>
-# 
-#  Copyright (C) 2004-2007
-#      Task-intelligence Research Group,
-#      Intelligent Systems Research Institute,
-#      National Institute of
-#          Advanced Industrial Science and Technology (AIST), Japan
-#      All rights reserved.
-# 
-#  $Id: cxx_gen.py,v 1.8.2.1 2007/07/20 17:28:56 n-ando Exp $
-# 
-
-#
-#  $Log: cxx_gen.py,v $
-#  Revision 1.8.2.1  2007/07/20 17:28:56  n-ando
-#  A fix for win32 porting.
-#
-#  Revision 1.8  2007/05/29 01:44:29  n-ando
-#  make clean target was modified to delete *Compl.o
-#
-#  Revision 1.7  2007/04/23 01:41:16  n-ando
-#  New option "--config" and configuration template code were added.
-#
-#  Revision 1.6  2007/04/13 15:05:50  n-ando
-#  Now RTC::OK becomes RTC::RTC_OK in RTC.idl.
-#
-#  Revision 1.5  2007/01/14 23:38:30  n-ando
-#  Updated to use setModuleInitProc() to initialize component locally.
-#
-#  Revision 1.4  2007/01/11 07:46:38  n-ando
-#  Modified for OMG RTC specificatin and OpenRTM-aist-0.4.0.
-#  Almost all template codes were modified according to the new framework.
-#
-#  Revision 1.3  2005/09/08 09:23:55  n-ando
-#  - A bug fix for merge function.
-#
-#  Revision 1.2  2005/09/06 14:37:03  n-ando
-#  rtc-template's command options and data structure for ezt (Easy Template)
-#  are changed for RTComponent's service features.
-#  Now rtc-template can generate services' skeletons, stubs and
-#  implementation files.
-#  The implementation code generation uses omniidl's IDL parser.
-#
-#  Revision 1.1  2005/08/26 12:02:14  n-ando
-#  This code generator module uses ezt (Easy Template).
-#
-#  Revision 1.1.1.1  2005/05/12 09:06:18  n-ando
-#  Public release.
-#
-#
-
-import re
-import os
-import sys
-import StringIO
-import ezt
-import gen_base
-
-
-def description():
-	return "C++ component code generator"
-
-def usage_short():
-	"""
-	C++ generator specific usage (short version)
-	"""
-	return """
-Options for C++ backend:
-
-    [--svc-impl-suffix[=suffix]]          Suffix of implementation class
-    [--svc-skel-suffix[=suffix]]          Suffix of server skeleton files
-    [--svc-stub-suffix[=suffix]]          Suffix of client stub files
-"""
-
-def usage():
-	"""
-	C++ generator specific usage
-	"""
-	return """
--------------------------------
-  Help for C++ code geenrator
--------------------------------
-    --svc-impl-suffix=[Suffix]:
-        Specify the suffix for implementation class name. This suffix is also
-        used for implementation class header file and code file.
-	
-    --svc-skel-suffix=[Suffix]:
-        Specify the suffix for server skeleton files.
-	
-    --svc-stub-suffix=[Suffix]:
-        Specify the suffix for client stub files.
-
-C++ code generator generates the following files.
-    [Component name].h.............Component class header
-    [Component name].cpp...........Component class soruce code
-    [Component name]Comp.cpp.......Component startup code
-    [IDL basename]Skel.h...........Server skeleton header
-    [IDL basename]Skel.cpp.........Server skeleton source code
-    [IDL basename]Stub.h...........Client stub header
-    [IDL basename]Stub.cpp.........Client stub source code
-    [IDL basename]SVC_impl.h.......Server implementation header
-    [IDL basename]SVC_impl.cpp.....Server implementation source code
-    Makefile.[Component name]......Makefile to compile this codes
-    README.[Component name]........Specification template of the component
-
- Suffixes (Skel, Stub, SVC_impl) can be specified --svc-*-suffix option
-
- Other CORBA implementation specific skeleton/stub code would be generated.
- --omniORB--
-    [IDL basename].hh..............Client stub header
-    [IDL basename]SK.cc............Server skeleton source code
-    [IDL basename]DynSK.cc.........Dynamic server skeleton source code
- --TAO--
-    [IDL basename]S.h..............Server skeleton header
-    [IDL basename]S.h..............Server skeleton source code
-    [IDL basename]C.h..............Client stub header
-    [IDL basename]C.h..............Client stub source code
- --MICO--
-    [IDL basename].h...............Server skeleton header
-    [IDL basename]_skel.cc.........Server skeleton source code
-    [IDL basename].h...............Client stub header
-    [IDL basename].cc..............Client stub source code
-
-"""
-
-def get_opt_fmt():
-	opt_args_fmt = ["svc-impl-suffix=",
-			"svc-skel-suffix=",
-			"svc-stub-suffix="]
-	return opt_args_fmt
-
-	
-#------------------------------------------------------------
-# Component header template code
-#------------------------------------------------------------
-comp_header = """// -*- C++ -*-
-/*!
- * @file  [fname_h]
- * @brief [module.desc]
- * @date  [rcs_date]
- *
- * [rcs_id]
- */
-
-#ifndef [u_name]_H
-#define [u_name]_H
-
-#include <rtm/Manager.h>
-#include <rtm/DataFlowComponentBase.h>
-#include <rtm/CorbaPort.h>
-#include <rtm/DataInPort.h>
-#include <rtm/DataOutPort.h>
-#include <rtm/idl/BasicDataTypeSkel.h>
-
-// Service implementation headers
-// <rtc-template block="service_impl_h">
-// </rtc-template>
-
-// Service Consumer stub headers
-// <rtc-template block="consumer_stub_h">
-// </rtc-template>
-
-using namespace RTC;
-
-class [module.name]
-  : public RTC::DataFlowComponentBase
-{
- public:
-  [module.name](RTC::Manager* manager);
-  ~[module.name]();
-
-  // The initialize action (on CREATED->ALIVE transition)
-  // formaer rtc_init_entry() 
- virtual RTC::ReturnCode_t onInitialize();
-
-  // The finalize action (on ALIVE->END transition)
-  // formaer rtc_exiting_entry()
-  // virtual RTC::ReturnCode_t onFinalize();
-
-  // The startup action when ExecutionContext startup
-  // former rtc_starting_entry()
-  // virtual RTC::ReturnCode_t onStartup(RTC::UniqueId ec_id);
-
-  // The shutdown action when ExecutionContext stop
-  // former rtc_stopping_entry()
-  // virtual RTC::ReturnCode_t onShutdown(RTC::UniqueId ec_id);
-
-  // The activated action (Active state entry action)
-  // former rtc_active_entry()
-  // virtual RTC::ReturnCode_t onActivated(RTC::UniqueId ec_id);
-
-  // The deactivated action (Active state exit action)
-  // former rtc_active_exit()
-  // virtual RTC::ReturnCode_t onDeactivated(RTC::UniqueId ec_id);
-
-  // The execution action that is invoked periodically
-  // former rtc_active_do()
-  // virtual RTC::ReturnCode_t onExecute(RTC::UniqueId ec_id);
-
-  // The aborting action when main logic error occurred.
-  // former rtc_aborting_entry()
-  // virtual RTC::ReturnCode_t onAborting(RTC::UniqueId ec_id);
-
-  // The error action in ERROR state
-  // former rtc_error_do()
-  // virtual RTC::ReturnCode_t onError(RTC::UniqueId ec_id);
-
-  // The reset action that is invoked resetting
-  // This is same but different the former rtc_init_entry()
-  // virtual RTC::ReturnCode_t onReset(RTC::UniqueId ec_id);
-  
-  // The state update action that is invoked after onExecute() action
-  // no corresponding operation exists in OpenRTm-aist-0.2.0
-  // virtual RTC::ReturnCode_t onStateUpdate(RTC::UniqueId ec_id);
-
-  // The action that is invoked when execution context's rate is changed
-  // no corresponding operation exists in OpenRTm-aist-0.2.0
-  // virtual RTC::ReturnCode_t onRateChanged(RTC::UniqueId ec_id);
-
-
- protected:
-  // Configuration variable declaration
-  // <rtc-template block="config_declare">
-  // </rtc-template>
-
-  // DataInPort declaration
-  // <rtc-template block="inport_declare">
-  // </rtc-template>
-
-  // DataOutPort declaration
-  // <rtc-template block="outport_declare">
-  // </rtc-template>
-
-  // CORBA Port declaration
-  // <rtc-template block="corbaport_declare">
-  // </rtc-template>
-
-  // Service declaration
-  // <rtc-template block="service_declare">
-  // </rtc-template>
-
-  // Consumer declaration
-  // <rtc-template block="consumer_declare">
-  // </rtc-template>
-
- private:
-  int dummy;
-
-};
-
-
-extern "C"
-{
-  void [module.name]Init(RTC::Manager* manager);
-};
-
-#endif // [u_name]_H
-"""
-
-
-#------------------------------------------------------------
-# Component source template code
-#------------------------------------------------------------
-comp_soruce = """// -*- C++ -*-
-/*!
- * @file  [fname_cpp]
- * @brief [module.desc]
- * [rcs_date]
- *
- * [rcs_id]
- */
-
-#include "[fname_h]"
-
-// Module specification
-// <rtc-template block="module_spec">
-// </rtc-template>
-
-[module.name]::[module.name](RTC::Manager* manager)
-  : RTC::DataFlowComponentBase(manager),
-    // <rtc-template block="initializer">
-    // </rtc-template>
-	dummy(0)
-{
-  // Registration: InPort/OutPort/Service
-  // <rtc-template block="registration">
-  // </rtc-template>
-
-}
-
-[module.name]::~[module.name]()
-{
-}
-
-
-RTC::ReturnCode_t [module.name]::onInitialize()
-{
-  // <rtc-template block="bind_config">
-  // </rtc-template>
-  return RTC::RTC_OK;
-}
-
-
-[for activity]
-/*
-RTC::ReturnCode_t [module.name]::[activity.name]([activity.args])
-{
-  return RTC::RTC_OK;
-}
-*/
-[end]
-
-
-extern "C"
-{
- 
-  void [module.name]Init(RTC::Manager* manager)
-  {
-    RTC::Properties profile([l_name]_spec);
-    manager->registerFactory(profile,
-                             RTC::Create<[module.name]>,
-                             RTC::Delete<[module.name]>);
-  }
-  
-};
-
-
-"""
-
-
-#------------------------------------------------------------
-# Component soruce template
-#------------------------------------------------------------
-comp_compsrc = """// -*- C++ -*-
-/*!
- * @file [module.name]Comp.cpp
- * @brief Standalone component
- * @date [rcs_date]
- *
- * [rcs_id]
- */
-
-#include <rtm/Manager.h>
-#include <iostream>
-#include <string>
-#include "[fname_h]"
-
-
-void MyModuleInit(RTC::Manager* manager)
-{
-  [module.name]Init(manager);
-  RTC::RtcBase* comp;
-
-  // Create a component
-  comp = manager->createComponent("[module.name]");
-
-
-  // Example
-  // The following procedure is examples how handle RT-Components.
-  // These should not be in this function.
-
-  // Get the component's object reference
-//  RTC::RTObject_var rtobj;
-//  rtobj = RTC::RTObject::_narrow(manager->getPOA()->servant_to_reference(comp));
-
-  // Get the port list of the component
-//  PortList* portlist;
-//  portlist = rtobj->get_ports();
-
-  // getting port profiles
-//  std::cout << "Number of Ports: ";
-//  std::cout << portlist->length() << std::endl << std::endl; 
-//  for (CORBA::ULong i(0), n(portlist->length()); i < n; ++i)
-//  {
-//    Port_ptr port;
-//    port = (*portlist)[begin_brace]i[end_brace];
-//    std::cout << "Port" << i << " (name): ";
-//    std::cout << port->get_port_profile()->name << std::endl;
-//    
-//    RTC::PortInterfaceProfileList iflist;
-//    iflist = port->get_port_profile()->interfaces;
-//    std::cout << "---interfaces---" << std::endl;
-//    for (CORBA::ULong i(0), n(iflist.length()); i < n; ++i)
-//    {
-//      std::cout << "I/F name: ";
-//      std::cout << iflist[begin_brace]i[end_brace].instance_name << std::endl;
-//      std::cout << "I/F type: ";
-//      std::cout << iflist[begin_brace]i[end_brace].type_name << std::endl;
-//      const char* pol;
-//      pol = iflist[begin_brace]i[end_brace].polarity == 0 ? "PROVIDED" : "REQUIRED";
-//      std::cout << "Polarity: " << pol << std::endl;
-//    }
-//    std::cout << "---properties---" << std::endl;
-//    NVUtil::dump(port->get_port_profile()->properties);
-//    std::cout << "----------------" << std::endl << std::endl;
-//  }
-
-  return;
-}
-
-int main (int argc, char** argv)
-{
-  RTC::Manager* manager;
-  manager = RTC::Manager::init(argc, argv);
-
-  // Initialize manager
-  manager->init(argc, argv);
-
-  // Set module initialization proceduer
-  // This procedure will be invoked in activateManager() function.
-  manager->setModuleInitProc(MyModuleInit);
-
-  // Activate manager and register to naming service
-  manager->activateManager();
-
-  // run the manager in blocking mode
-  // runManager(false) is the default.
-  manager->runManager();
-
-  // If you want to run the manager in non-blocking mode, do like this
-  // manager->runManager(true);
-
-  return 0;
-}
-"""
-
-
-#------------------------------------------------------------
-# Makefile template
-#------------------------------------------------------------
-makefile = """# -*- Makefile -*-
-#
-# @file  Makefile.[module.name]
-# @brief RTComponent makefile for "[module.name] component"
-# @date  [rcs_date]
-#
-# This file is generated by rtc-template with the following argments.
-#
-[for fmtd_args]#  [fmtd_args]
-[end]#
-#
-# [rcs_id]
-#
-CXXFLAGS = `rtm-config --cflags`
-LDFLAGS  = `rtm-config --libs`
-SHFLAGS  = -shared
-
-IDLC     = `rtm-config --idlc`
-IDLFLAGS = `rtm-config --idlflags` -I`rtm-config --prefix`/include/rtm/idl
-WRAPPER  = rtm-skelwrapper
-WRAPPER_FLAGS = --include-dir="" --skel-suffix=Skel --stub-suffix=Stub
-
-SKEL_OBJ = [for service_idl][service_idl.skel_basename].o [end] \
-	[for consumer_idl][consumer_idl.stub_basename].o [end]
-STUB_OBJ = [for service_idl][service_idl.stub_basename].o [end]
-IMPL_OBJ = [for service_idl][service_idl.impl_basename].o [end]
-OBJS     = [module.name].o $(SKEL_OBJ) $(IMPL_OBJ)
-
-.SUFFIXES : .so
-
-all: [module.name].so [module.name]Comp
-
-
-.cpp.o:
-	rm -f $@
-	$(CXX) $(CXXFLAGS) -c -o $@ $<
-
-.o.so:
-	rm -f $@
-	$(CXX) $(SHFLAGS) -o $@ $(OBJS) $(LDFLAGS)
-
-[module.name]Comp: [module.name]Comp.o $(OBJS)
-	$(CXX) -o $@ $(OBJS) [module.name]Comp.o $(LDFLAGS) 
-
-
-clean: clean_objs clean_skelstub
-	rm -f *~
-
-clean_objs:
-	rm -f $(OBJS) [module.name]Comp.o [module.name].so [module.name]Comp
-
-clean_skelstub:
-	rm -f *[skel_suffix].h *[skel_suffix].cpp
-	rm -f *[stub_suffix].h *[stub_suffix].cpp
-
-
-
-[for service_idl]
-[service_idl.skel_basename].cpp : [service_idl.idl_fname]
-	$(IDLC) $(IDLFLAGS) [service_idl.idl_fname]
-	$(WRAPPER) $(WRAPPER_FLAGS) --idl-file=[service_idl.idl_fname]
-[service_idl.skel_basename].h : [service_idl.idl_fname]
-	$(IDLC) $(IDLFLAGS) [service_idl.idl_fname]
-	$(WRAPPER) $(WRAPPER_FLAGS) --idl-file=[service_idl.idl_fname]
-[service_idl.stub_basename].cpp : [service_idl.idl_fname]
-	$(IDLC) $(IDLFLAGS) [service_idl.idl_fname]
-	$(WRAPPER) $(WRAPPER_FLAGS) --idl-file=[service_idl.idl_fname]
-[service_idl.stub_basename].h : [service_idl.idl_fname]
-	$(IDLC) $(IDLFLAGS) [service_idl.idl_fname]
-	$(WRAPPER) $(WRAPPER_FLAGS) --idl-file=[service_idl.idl_fname]
-[end]
-
-[for consumer_idl]
-[consumer_idl.stub_basename].cpp : [consumer_idl.idl_fname]
-	$(IDLC) $(IDLFLAGS) [consumer_idl.idl_fname]
-	$(WRAPPER) $(WRAPPER_FLAGS) --idl-file=[consumer_idl.idl_fname]
-[consumer_idl.stub_basename].h : [consumer_idl.idl_fname]
-	$(IDLC) $(IDLFLAGS) [consumer_idl.idl_fname]
-	$(WRAPPER) $(WRAPPER_FLAGS) --idl-file=[consumer_idl.idl_fname]
-[end]
-
-
-[module.name].so: $(OBJS)
-[module.name].o: [module.name].h \
-	[for service_idl][service_idl.skel_basename].h [service_idl.impl_basename].h [end] \
-	[for consumer_idl][consumer_idl.stub_basename].h [end]
-[module.name]Comp.o: [module.name]Comp.cpp [module.name].cpp [module.name].h [for service_idl][service_idl.skel_basename].h [service_idl.impl_basename].h [end]
-
-[for service_idl]
-[service_idl.impl_basename].o: [service_idl.impl_basename].cpp [service_idl.impl_basename].h [service_idl.skel_basename].h [service_idl.stub_basename].h
-[service_idl.skel_basename].o: [service_idl.skel_basename].cpp [service_idl.skel_basename].h [service_idl.stub_basename].h
-[service_idl.stub_basename].o: [service_idl.stub_basename].cpp [service_idl.stub_basename].h
-[end]
-
-[for consumer_idl]
-[consumer_idl.stub_basename].o: [consumer_idl.stub_basename].cpp [consumer_idl.stub_basename].h
-[end]
-
-# end of Makefile
-"""
-
-
-#============================================================
-# Replaced strings definition for <rtc-template> tags
-#============================================================
-service_impl_h = """[for service_idl]#include "[service_idl.impl_h]"
-[end]"""
-consumer_stub_h = """[for consumer_idl]#include "[consumer_idl.stub_h]"
-[end]"""
-
-module_spec = """static const char* [l_name]_spec[] =
-  {
-    "implementation_id", "[module.name]",
-    "type_name",         "[module.name]",
-    "description",       "[module.desc]",
-    "version",           "[module.version]",
-    "vendor",            "[module.vendor]",
-    "category",          "[module.category]",
-    "activity_type",     "[module.comp_type]",
-    "max_instance",      "[module.max_inst]",
-    "language",          "C++",
-    "lang_type",         "compile",
-    // Configuration variables
-[for config]    "conf.default.[config.name]", "[config.default]",
-[end]
-    ""
-  };"""
-
-config_declare = \
-"""  [for config][config.type] m_[config.name];
-  [end]"""
-  
-
-inport_declare = \
-"""  [for inport][inport.type] m_[inport.name];
-  InPort<[inport.type]> m_[inport.name]In;
-  [end]"""
-
-outport_declare = \
-"""  [for outport][outport.type] m_[outport.name];
-  OutPort<[outport.type]> m_[outport.name]Out;
-  [end]"""
-
-corbaport_declare = \
-"""  [for corbaport]RTC::CorbaPort m_[corbaport.name]Port;
-  [end]"""
- 
-service_declare = \
-"""  [for service][service.type]SVC_impl m_[service.name];
-  [end]"""
-
-consumer_declare = \
-"""  [for consumer]RTC::CorbaConsumer<[consumer.type]> m_[consumer.name];
-  [end]"""
-
-initializer = \
-"""    [for inport]m_[inport.name]In("[inport.name]", m_[inport.name]),
-    [end][for outport]m_[outport.name]Out("[outport.name]", m_[outport.name]),
-    [end][for corbaport]m_[corbaport.name]Port("[corbaport.name]"),[end]"""
-
-
-registration = \
-"""  // Set InPort buffers
-  [for inport]registerInPort("[inport.name]", m_[inport.name]In);
-  [end]
-  // Set OutPort buffer
-  [for outport]registerOutPort("[outport.name]", m_[outport.name]Out);
-  [end]
-  // Set service provider to Ports
-  [for service]m_[service.port]Port.registerProvider("[service.name]", "[service.type]", m_[service.name]);
-  [end]
-  // Set service consumers to Ports
-  [for consumer]m_[consumer.port]Port.registerConsumer("[consumer.name]", "[consumer.type]", m_[consumer.name]);
-  [end]
-  // Set CORBA Service Ports
-  [for corbaport]registerPort(m_[corbaport.name]Port);
-  [end]"""
-
-bind_config = \
-"""  // Bind variables and configuration variable
-  [for config]bindParameter("[config.name]", m_[config.name], "[config.default]");
-  [end]"""
-
-#------------------------------------------------------------
-
-
-#============================================================
-# Classes and Functions
-#============================================================
-
-class Struct:
-	def __init__(self):
-		return
-
-
-def MakeSuffix(opts, dict):
-	impl_suffix = "SVC_impl"
-	skel_suffix = "Skel"
-	stub_suffix = "Stub"
-	for opt, arg in opts:
-		if opt.find("--svc-impl-suffix") == 0:
-			impl_suffix = arg
-		if opt.find("--svc-skel-suffix") == 0:
-			skel_suffix = arg
-		if opt.find("--svc-stub-suffix") == 0:
-			stub_suffix = arg
-	dict["impl_suffix"] = impl_suffix
-	dict["skel_suffix"] = skel_suffix
-	dict["stub_suffix"] = stub_suffix
-
-
-def MakeServiceIDL(dict):
-	for d in dict["service_idl"]:
-		d.impl_basename = d.idl_basename + dict["impl_suffix"]
-		d.impl_h        = d.impl_basename + ".h"
-		d.impl_cpp      = d.impl_basename + ".cpp"
-		d.skel_basename = d.idl_basename + dict["skel_suffix"]
-		d.skel_h        = d.skel_basename + ".h"
-		d.skel_cpp      = d.skel_basename + ".cpp"
-		d.stub_suffix   = dict["stub_suffix"]
-		d.stub_basename = d.idl_basename + dict["stub_suffix"]
-		d.stub_h        = d.stub_basename + ".h"
-		d.stub_cpp      = d.stub_basename + ".cpp"
-
-
-def MakeConsumerIDL(dict):
-	conslist = []
-	for cons in dict["consumer_idl"]:
-		dup = False
-		for svc in dict["service_idl"]:
-			if cons.idl_fname == svc.idl_fname:
-				dup = True
-		if not dup:
-			tmp = cons
-			tmp.stub_suffix   = dict["stub_suffix"]
-			tmp.stub_basename = tmp.idl_basename \
-			    + dict["stub_suffix"]
-			tmp.stub_h        = tmp.stub_basename + ".h"
-			tmp.stub_cpp      = tmp.stub_basename + ".cpp"
-			conslist.append(tmp)
-	dict["consumer_idl"] = conslist
-
-
-def MakeActivityFuncs(dict):
-	acts = (("onFinalize",    ""), \
-		("onStartup",     "RTC::UniqueId ec_id"), \
-		("onShutdown",    "RTC::UniqueId ec_id"), \
-		("onActivated",   "RTC::UniqueId ec_id"), \
-		("onDeactivated", "RTC::UniqueId ec_id"), \
-		("onExecute",     "RTC::UniqueId ec_id"), \
-		("onAborting",    "RTC::UniqueId ec_id"), \
-		("onError",       "RTC::UniqueId ec_id"), \
-		("onReset",       "RTC::UniqueId ec_id"), \
-		("onStateUpdate", "RTC::UniqueId ec_id"), \
-		("onRateChanged", "RTC::UniqueId ec_id"))
-	actlist = []
-	for name, args in acts:
-		a = Struct()
-		a.name = name
-		a.args = args
-		actlist.append(a)
-
-	dict["activity"] = actlist
-
-
-class cxx_gen(gen_base.gen_base):
-	"""
-	C++ component source code generator
-	"""
-	_fname_space = 16
-	def __init__(self, data, opts):
-		self.data = data.copy()
-		
-		MakeSuffix(opts, self.data)
-		MakeServiceIDL(self.data)
-		MakeConsumerIDL(self.data)
-		MakeActivityFuncs(self.data)
-		self.data["begin_brace"] = "["
-		self.data["end_brace"] = "]"
-		self.data["rcs_date"] = "$" + "Date" + "$"
-		self.data["rcs_id"] = "$" + "Id" + "$"
-		self.data["fname_h"] = self.data["fname"] + ".h"
-		self.data["fname_cpp"] = self.data["fname"] + ".cpp"
-		self.data["fname_comp"] = self.data["fname"] + "Comp.cpp"
-		self.data["makefile"] = "Makefile." + self.data["fname"]
-		self.data["u_name"] = self.data["module"].name.upper()
-		self.data["l_name"] = self.data["module"].name.lower()
-
-
-		self.tags = {}
-		self.tags["service_impl_h"]    = service_impl_h
-		self.tags["consumer_stub_h"]   = consumer_stub_h
-		self.tags["module_spec"]       = module_spec
-		self.tags["config_declare"]    = config_declare
-		self.tags["inport_declare"]    = inport_declare
-		self.tags["outport_declare"]   = outport_declare
-		self.tags["corbaport_declare"] = corbaport_declare
-		self.tags["service_declare"]   = service_declare
-		self.tags["consumer_declare"]  = consumer_declare
-		self.tags["initializer"]       = initializer
-		self.tags["registration"]      = registration
-		self.tags["bind_config"]       = bind_config
-
-		self.gen_tags(self.tags)
-		return
-
-
-	def print_header(self):
-		"""
-		Generate component class header
-		"""
-		self.gen(self.data["fname_h"],
-			 comp_header, self.data, self.tags)
-		return
-
-
-	def print_source(self):
-		"""
-		Generate component class source code
-		"""
-		self.gen(self.data["fname_cpp"],
-			 comp_soruce, self.data, self.tags)
-		return
-
-
-	def print_compsrc(self):
-		"""
-		Generate component source code
-		"""
-		self.gen(self.data["fname_comp"],
-			 comp_compsrc, self.data, self.tags)
-		return
-
-
-	def print_makefile(self):
-		"""
-		Generate Makefile
-		"""
-		self.gen(self.data["makefile"],
-			 makefile, self.data, self.tags)
-
-
-	def print_impl(self):
-		for svc_idl in self.data["service_idl"]:
-			fd_h = None
-			fd_cpp = None
-			lines_h = None
-			lines_cpp = None
-			if not os.access(svc_idl.idl_fname, os.F_OK):
-				sys.stderr.write("Error: IDL file \"" \
-						 + svc_idl.idl_fname \
-						 + "\" not found.\n")
-				sys.exit(1)
-			fd_h, lines_h = \
-			    self.check_overwrite(svc_idl.impl_h)
-			fd_cpp, lines_cpp = \
-			    self.check_overwrite(svc_idl.impl_cpp)
-			if not fd_h:
-				sys.stderr.write("Cannot open file:" + 
-						 svc_idl.impl_h + "\n")
-				sys.exit(1)
-			if not fd_cpp:
-				sys.stderr.write("Cannot open file:" + 
-						 svc_idl.impl_cpp + "\n")
-				sys.exit(1)
-			if lines_h or lines_cpp:
-				sys.stderr.write("Merge of service impl." +
-						 "code is not supported.\n")
-				return
-
-			try:
-				idl_include = self.data["idl_include"]
-				impl_suffix = self.data["impl_suffix"]
-				skel_suffix = self.data["skel_suffix"]
-				import cxx_svc_impl
-				ifs = cxx_svc_impl.generate(svc_idl.idl_fname,
-							    idl_include,
-							    impl_suffix,
-							    skel_suffix,
-							    fd_h, fd_cpp)
-				print "  File \"" \
-				    + svc_idl.impl_h \
-				    + "\" was generated."
-				print "  File \"" \
-				    + svc_idl.impl_cpp \
-				    + "\" was generated."
-			except:
-				sys.stderr.write("Generate error: " \
-						 + svc_idl.impl_h
-						 + ", "
-						 + svc_idl.impl_cpp + "\n")
-				
-	def print_all(self):
-		self.print_impl()
-		self.print_header()
-		self.print_source()
-		self.print_compsrc()
-		self.print_makefile()
-		return
-
-
-class idl2char:
-	def __init__(self, filename = None):
-		self.lines = ""
-		self.inComment = False
-		if filename:
-			f = open(filename)
-			l = f.readlines()
-			self.erase_comments(l)
-			f.close()
-
-	def open_file(self, filename):
-		f = open(filename)
-		l = f.readlines()
-		self.erase_comments(l)
-		f.close()
-
-	def cleanup():
-		self.lines = ""
-
-	def erase_comments(self, lines):
-		for l in lines:
-			m = re.search("/\*.*\*/", l)
-			if m:
-				l = l.replace(m.group(), "")
-				
-			m = re.search(".*\*/", l)
-			if m:
-				l = l.replace(m.group(), "")
-				if self.inComment == True:
-					self.inComment = False
-
-			m = re.search("/\*.*$", l)
-			if m:
-				l = l.replace(m.group(), "")
-				if self.inComment == False:
-					self.inComment = True
-
-			m = re.search("//.*$", l)
-			if m:
-				l = l.replace(m.group(), "")
-
-			m = re.search("\s+$", l)
-			if m:
-				l = l.replace(m.group(), "")
-				l = l + "\n"
-
-			m = re.search("\S", l)
-			if m:
-				if not self.inComment:
-					self.lines += l
-
-					
-	def get_lines(self):
-		return self.lines
-
-	def make_chardata(self, var_name):
-		self.lines = self.lines.replace("\n","\\n\\\n")
-		self.lines = self.lines.replace("\"","\\\"")
-		self.lines = "static char* " + var_name  \
-		    + " = \"\\\n" + self.lines
-		self.lines += "\";\n"
-		return self.lines
-
-	def add_slash(self):
-		self.lines = self.lines.replace("\n","\\\n")
-		return self.lines
-
-	def write_file(self, filename):
-		f = open(filename, "w")
-		f.write(self.lines)
-		f.close()
-
-

Deleted: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_svc_impl.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_svc_impl.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/cxx_svc_impl.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,385 +0,0 @@
-#!/usr/bin/env python
-# -*- python -*-
-#
-#  @file cxx_svc_impl.py
-#  @brief rtc-template C++ service source code generator class
-#  @date $Date: 2007/02/07 02:51:49 $
-#  @author Noriaki Ando <n-ando at aist.go.jp>
-# 
-#  Copyright (C) 2005-2007
-#      Task-intelligence Research Group,
-#      Intelligent Systems Research Institute,
-#      National Institute of
-#          Advanced Industrial Science and Technology (AIST), Japan
-#      All rights reserved.
-# 
-#  $Id: cxx_svc_impl.py,v 1.4 2007/02/07 02:51:49 n-ando Exp $
-# 
-
-#
-# $Log: cxx_svc_impl.py,v $
-# Revision 1.4  2007/02/07 02:51:49  n-ando
-# RCS Id tag was removed from template source code.
-#
-# Revision 1.3  2007/01/11 07:44:39  n-ando
-# Now service implementation class does not inherit RtcServiceBase.
-# The implementation template was changed.
-#
-# Revision 1.2  2005/09/06 14:37:18  n-ando
-# rtc-template's command options and data structure for ezt (Easy Template)
-# are changed for RTComponent's service features.
-# Now rtc-template can generate services' skeletons, stubs and
-# implementation files.
-# The implementation code generation uses omniidl's IDL parser.
-#
-# Revision 1.1  2005/08/29 17:50:57  n-ando
-# The first version.
-#
-#
-
-import string
-import os
-
-# omniidl modules
-import _omniidl
-from omniidl import idlast, idlvisitor
-from omniidl_be.cxx import ast, util, id, types, output
-
-# import myself
-import cxx_svc_impl
-self = cxx_svc_impl
-
-
-#------------------------------------------------------------
-# Example code
-#------------------------------------------------------------
-interface_def = """\
-/*
- * Example class implementing IDL interface @fq_name@
- */
-class @impl_fqname@
- : public virtual @fq_POA_name@,
-   public virtual PortableServer::RefCountServantBase
-{
- private:
-   // Make sure all instances are built on the heap by making the
-   // destructor non-public
-   //virtual ~@impl_name@();
-
- public:
-   // standard constructor
-   @impl_name@();
-   virtual ~@impl_name@();
-
-   // attributes and operations
-   @operations@
-};
-"""
-
-interface_code = """\
-/*
- * Example implementational code for IDL interface @fqname@
- */
- at impl_fqname@::@impl_name@()
-{
-  // Please add extra constructor code here.
-}
-
-
- at impl_fqname@::~@impl_name@()
-{
-  // Please add extra destructor code here.
-}
-
-
-/*
- * Methods corresponding to IDL attributes and operations
- */
- at operations@
-
-// End of example implementational code
-"""
-
-class_h = """\
-// -*-C++-*-
-/*!
- * @atmark at file  @impl_h@
- * @atmark at brief Service implementation header of @file@
- *
- */
-
-#include "@skel_h@"
-
-
-#ifndef @include_guard@
-#define @include_guard@
- 
- at interfaces@
-
-#endif // @include_guard@
-
-"""
-
-class_cpp = """\
-// -*-C++-*-
-/*!
- * @atmark at file  @impl_cpp@
- * @atmark at brief Service implementation code of @file@
- *
- */
-
-#include "@impl_h@"
-
- at interfaces@
-"""
-
-def generate(idl_file, preproc_args, impl_suffix, skel_suffix = "Skel", fd_h=None, fd_cpp=None):
-	basename = idl_file.replace(".idl","")
-	preprocessor_cmd = "omnicpp"
-	preprocessor_opt = "-I" + string.join(preproc_args, " -I")
-
-	preproc_cmd = '%s %s %s' % (preprocessor_cmd,\
-				  preprocessor_opt, idl_file)
-
-	file = os.popen(preproc_cmd, "r")
-
-	skel_filename = basename + skel_suffix + ".h"
-	idl_filename = idl_file
-
-	# ignore the following operations
-	ignore_operations = ["profile"]
-	
-	tree = _omniidl.compile(file)
-	ast.__init__(tree)
-
-	cxx_svc_impl.__init__(idl_filename, \
-					  basename, \
-					  skel_filename, \
-					  impl_suffix, \
-					  ignore_operations, \
-					  fd_h, \
-					  fd_cpp)
-	ifs = cxx_svc_impl.run(tree)
-	file.close()
-	_omniidl.clear()
-	return ifs
-
-
-#============================================================
-# This module's __init__()
-#============================================================
-def __init__(idl_filename, impl_basename, skel_filename, \
-		suffix = "_impl", ignore_op = [], fd_h = None, fd_cpp = None):
-	self.idl_filename = idl_filename
-	self.suffix = suffix
-	self.impl_h_filename = impl_basename + self.suffix + ".h"
-	self.impl_cpp_filename = impl_basename + self.suffix + ".cpp"
-	self.skel_filename = skel_filename
-	self.ignore_op = ignore_op
-
-	self.include_guard = self.impl_h_filename.upper().replace(".","_")
-
-	if fd_h == None:
-		self.stream_h = \
-		    output.Stream(output.createFile(self.impl_h_filename), 2)
-	else:
-		self.stream_h = output.Stream(fd_h, 2)
-		
-	if fd_cpp == None:
-		self.stream_cpp = \
-		    output.Stream(output.createFile(self.impl_cpp_filename), 2)
-	else:
-		self.stream_cpp = output.Stream(fd_cpp, 2)
-		
-	
-
-# Given an IDL name convert it into the fully qualified name of the
-# implementation class
-def impl_fullname(name):
-    bits = name.suffix(self.suffix).fullName()
-    return string.join(bits, "_")
-
-# Convert an IDL name into the simple name of the implementation class
-def impl_simplename(name):
-    return impl_fullname(name)
-
-#
-# Main code entrypoint
-#
-def run(tree):
-	# The implementation template code stream
-	impl_cpp = output.StringStream()
-	# The implementation template header stream
-	impl_h   = output.StringStream()
-	bii = BuildInterfaceImplementations(impl_h, impl_cpp, self.ignore_op)
-	tree.accept(bii)
-
-	# Generate mplementation class template header
-	stream_h.out(class_h,
-				 atmark = "@",
-				 impl_h = self.impl_h_filename,
-				 include_guard = self.include_guard,
-				 skel_h = self.skel_filename,
-				 file = self.idl_filename,
-				 interfaces = str(impl_h))
-	
-	# Generate implementation class template code
-	stream_cpp.out(class_cpp,
-				   atmark = "@",
-				   impl_cpp = self.impl_cpp_filename,
-				   impl_h = self.impl_h_filename,
-				   file = self.idl_filename,
-				   interfaces = str(impl_cpp))
-
-	self.ifs = []
-	for n in bii.allInterfaces():
-		self.ifs.append(string.join(n.scopedName(), "_") + self.suffix)
-	return self.ifs
-	
-	
-
-
-#============================================================
-# Build the interface implementations
-#============================================================
-class BuildInterfaceImplementations(idlvisitor.AstVisitor):
-
-	def __init__(self, stream_h, stream_cpp, ignore_operations):
-		self.stream_h = stream_h
-		self.stream_cpp = stream_cpp
-		self.ignore_operations = ignore_operations
-		# keep track of all interfaces for later use
-		self.__allInterfaces = []
-
-	# Returns the list of all present interfaces (each one will be
-	# implemented)
-	def allInterfaces(self):
-		return self.__allInterfaces[:]
-
-	# Tree walking code
-	def visitAST(self, node):
-		for n in node.declarations():
-			if ast.shouldGenerateCodeForDecl(n):
-				n.accept(self)
-
-	# modules can contain interfaces
-	def visitModule(self, node):
-		for n in node.definitions():
-			n.accept(self)
-
-	# interfaces cannot be further nested
-	def visitInterface(self, node):
-		self.__allInterfaces.append(node)
-	
-		scopedName = id.Name(node.scopedName())
-		
-		cxx_fqname = scopedName.fullyQualify()
-		impl_flat_name = impl_fullname(scopedName)
-
-		fqname = scopedName.fullyQualify(cxx = 0)
-
-		
-		# build methods corresponding to attributes, operations etc.
-		# attributes[] and operations[] will contain lists of function
-		# signatures eg
-		#   [ char *echoString(const char *mesg) ]
-		attributes = []
-		operations = []
-		virtual_operations = []
-
-		# we need to consider all callables, including inherited ones
-		# since this implementation class is not inheriting from anywhere
-		# other than the IDL skeleton
-		allInterfaces = [node] + ast.allInherits(node)
-		allCallables = util.fold( map(lambda x:x.callables(), allInterfaces),
-								  [], lambda x, y: x + y )
-
-
-		# declarations[] contains a list of in-class decl signatures
-		# implementations[] contains a list of out of line impl signatures
-		# (typically differ by classname::)
-		declarations = []
-		implementations = []
-		
-		for c in allCallables:
-
-			if isinstance(c, idlast.Attribute) :
-				attrType = types.Type(c.attrType())
-				d_attrType = attrType.deref()
-
-				for i in c.identifiers():
-					attribname = id.mapID(i)
-					returnType = attrType.op(types.RET)
-					inType = attrType.op(types.IN)
-					attributes.append(returnType + " " + attribname + "()")
-					# need a set method if not a readonly attribute
-					if not c.readonly():
-						args = attribname + "(" + inType + ")"
-						declarations.append("void " + args)
-						implementations.append("void " + impl_flat_name +\
-											   "::" + args)
-					if not attribname in self.ignore_operations:
-						declarations.append(returnType + " " + attribname + "()")
-						implementations.append(returnType + " " + impl_flat_name+\
-										   "::" + attribname + "()")
-			elif isinstance(c, idlast.Operation):
-				params = []
-				for p in c.parameters():
-					paramType = types.Type(p.paramType())
-					cxx_type = paramType.op(types.direction(p), use_out = 0)
-					
-					argname = id.mapID(p.identifier())
-					params.append(cxx_type + " " + argname)
-
-				# deal with possible "context"
-				if c.contexts() != []:
-					params.append("CORBA::Context_ptr _ctxt")
-
-				return_type = types.Type(c.returnType()).op(types.RET)
-
-				opname = id.mapID(c.identifier())
-				if not opname in self.ignore_operations:
-					arguments = string.join(params, ", ")
-					args = opname + "(" + arguments + ")"
-					declarations.append(return_type + " " + args)
-					implementations.append(return_type + " " + \
-										   impl_flat_name + \
-										   "::" + args)
-			else:
-				util.fatalError("Internal error generating interface member")
-				raise "No code for interface member: " + repr(c)
-
-		# the class definition has no actual code...
-		defs = string.join(map(lambda x:x + ";\n", declarations), "")
-
-		# Output the class definition of the implementation
-		self.stream_h.out(interface_def,
-						  impl_fqname = impl_flat_name,
-						  impl_name = impl_flat_name,
-						  fq_name = fqname,
-						  fq_POA_name = "POA_" + cxx_fqname,
-						  operations = defs)
-
-		# Output the class methods implementations
-		impls = string.join(map(lambda x: x + """\
-
-{
-  // Please insert your code here and remove the following warning pragma
-  #warning "Code missing in function <""" + x + """>"
-}
-
-""",
-								implementations), "")
-		
-		self.stream_cpp.out(interface_code,
-							fqname = fqname,
-							impl_name = impl_flat_name,
-							impl_fqname = impl_flat_name,
-							operations = impls)
-
-
-if __name__ == "__main__":
-	import cxx_svc_impl
-	import sys
-	print "Interfaces:"
-	print cxx_svc_impl.generate(sys.argv[1], "SVC_impl")

Deleted: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/ezt.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/ezt.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/ezt.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,585 +0,0 @@
-#!/usr/bin/env python
-"""ezt.py -- easy templating
-
-ezt templates are very similar to standard HTML files.  But additionally
-they contain directives sprinkled in between.  With these directives
-it is possible to generate the dynamic content from the ezt templates.
-
-These directives are enclosed in square brackets.  If you are a 
-C-programmer, you might be familar with the #ifdef directives of the
-C preprocessor 'cpp'.  ezt provides a similar concept for HTML.  Additionally 
-EZT has a 'for' directive, which allows to iterate (repeat) certain 
-subsections of the template according to sequence of data items
-provided by the application.
-
-The HTML rendering is performed by the method generate() of the Template
-class.  Building template instances can either be done using external
-EZT files (convention: use the suffix .ezt for such files):
-
-    >>> template = Template("../templates/log.ezt")
-
-or by calling the parse() method of a template instance directly with 
-a EZT template string:
-
-    >>> template = Template()
-    >>> template.parse('''<html><head>
-    ... <title>[title_string]</title></head>
-    ... <body><h1>[title_string]</h1>
-    ...    [for a_sequence] <p>[a_sequence]</p>
-    ...    [end] <hr>
-    ...    The [person] is [if-any state]in[else]out[end].
-    ... </body>
-    ... </html>
-    ... ''')
-
-The application should build a dictionary 'data' and pass it together
-with the output fileobject to the templates generate method:
-
-    >>> data = {'title_string' : "A Dummy Page",
-    ...         'a_sequence' : ['list item 1', 'list item 2', 'another element'],
-    ...         'person': "doctor",
-    ...         'state' : None }
-    >>> import sys
-    >>> template.generate(sys.stdout, data)
-    <html><head>
-    <title>A Dummy Page</title></head>
-    <body><h1>A Dummy Page</h1>
-     <p>list item 1</p>
-     <p>list item 2</p>
-     <p>another element</p>
-     <hr>
-    The doctor is out.
-    </body>
-    </html>
-
-Template syntax error reporting should be improved.  Currently it is 
-very sparse (template line numbers would be nice):
-
-    >>> Template().parse("[if-any where] foo [else] bar [end unexpected args]")
-    Traceback (innermost last):
-      File "<stdin>", line 1, in ?
-      File "ezt.py", line 220, in parse
-        self.program = self._parse(text)
-      File "ezt.py", line 275, in _parse
-        raise ArgCountSyntaxError(str(args[1:]))
-    ArgCountSyntaxError: ['unexpected', 'args']
-    >>> Template().parse("[if unmatched_end]foo[end]")
-    Traceback (innermost last):
-      File "<stdin>", line 1, in ?
-      File "ezt.py", line 206, in parse
-        self.program = self._parse(text)
-      File "ezt.py", line 266, in _parse
-        raise UnmatchedEndError()
-    UnmatchedEndError
-
-
-Directives
-==========
-
- Several directives allow the use of dotted qualified names refering to objects
- or attributes of objects contained in the data dictionary given to the 
- .generate() method.
-
- Simple directives
- -----------------
-
-   [QUAL_NAME]
-
-   This directive is simply replaced by the value of identifier from the data 
-   dictionary.  QUAL_NAME might be a dotted qualified name refering to some
-   instance attribute of objects contained in the dats dictionary.
-   Numbers are converted to string though.
-
-   [include "filename"]  or [include QUAL_NAME]
-
-   This directive is replaced by content of the named include file.
-
- Block directives
- ----------------
-
-   [for QUAL_NAME] ... [end]
-   
-   The text within the [for ...] directive and the corresponding [end]
-   is repeated for each element in the sequence referred to by the qualified
-   name in the for directive.  Within the for block this identifiers now 
-   refers to the actual item indexed by this loop iteration.
-
-   [if-any QUAL_NAME [QUAL_NAME2 ...]] ... [else] ... [end]
-
-   Test if any QUAL_NAME value is not None or an empty string or list.  
-   The [else] clause is optional.  CAUTION: Numeric values are converted to
-   string, so if QUAL_NAME refers to a numeric value 0, the then-clause is
-   substituted!
-
-   [if-index INDEX_FROM_FOR odd] ... [else] ... [end]
-   [if-index INDEX_FROM_FOR even] ... [else] ... [end]
-   [if-index INDEX_FROM_FOR first] ... [else] ... [end]
-   [if-index INDEX_FROM_FOR last] ... [else] ... [end]
-   [if-index INDEX_FROM_FOR NUMBER] ... [else] ... [end]
-
-   These five directives work similar to [if-any], but are only useful 
-   within a [for ...]-block (see above).  The odd/even directives are 
-   for example useful to choose different background colors for adjacent rows 
-   in a table.  Similar the first/last directives might be used to
-   remove certain parts (for example "Diff to previous" doesn't make sense,
-   if there is no previous).
-
-   [is QUAL_NAME STRING] ... [else] ... [end]
-   [is QUAL_NAME QUAL_NAME] ... [else] ... [end]
-
-   The [is ...] directive is similar to the other conditional directives
-   above.  But it allows to compare two value references or a value reference
-   with some constant string.
- 
-"""
-#
-# Copyright (C) 2001-2002 Greg Stein. All Rights Reserved.
-#
-# Redistribution and use in source and binary forms, with or without 
-# modification, are permitted provided that the following conditions are 
-# met:
-#
-# * Redistributions of source code must retain the above copyright 
-#   notice, this list of conditions and the following disclaimer. 
-#
-# * Redistributions in binary form must reproduce the above copyright 
-#   notice, this list of conditions and the following disclaimer in the 
-#   documentation and/or other materials provided with the distribution. 
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
-# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
-# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
-# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE 
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
-# POSSIBILITY OF SUCH DAMAGE.
-#
-#
-# This software is maintained by Greg and is available at:
-#    http://viewcvs.sourceforge.net/
-# it is also used by the following projects:
-#    http://edna.sourceforge.net/
-#
-
-import string
-import re
-from types import StringType, IntType, FloatType
-import os
-
-#
-# This regular expression matches three alternatives:
-#   expr: DIRECTIVE | BRACKET | COMMENT
-#   DIRECTIVE: '[' ITEM (whitespace ITEM)* ']
-#   ITEM: STRING | NAME
-#   STRING: '"' (not-slash-or-dquote | '\' anychar)* '"'
-#   NAME: (alphanum | '_' | '-' | '.')+
-#   BRACKET: '[[]'
-#   COMMENT: '[#' not-rbracket* ']'
-#
-# When used with the split() method, the return value will be composed of
-# non-matching text and the two paren groups (DIRECTIVE and BRACKET). Since
-# the COMMENT matches are not placed into a group, they are considered a
-# "splitting" value and simply dropped.
-#
-_item = r'(?:"(?:[^\\"]|\\.)*"|[-\w.]+)'
-_re_parse = re.compile(r'\[(%s(?: +%s)*)\]|(\[\[\])|\[#[^\]]*\]' % (_item, _item))
-
-_re_args = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.]+')
-
-# block commands and their argument counts
-_block_cmd_specs = { 'if-index':2, 'for':1, 'is':2 }
-_block_cmds = _block_cmd_specs.keys()
-
-# two regular expresssions for compressing whitespace. the first is used to
-# compress any whitespace including a newline into a single newline. the
-# second regex is used to compress runs of whitespace into a single space.
-_re_newline = re.compile('[ \t\r\f\v]*\n\\s*')
-_re_whitespace = re.compile(r'\s\s+')
-
-# this regex is used to substitute arguments into a value. we split the value,
-# replace the relevant pieces, and then put it all back together. splitting
-# will produce a list of: TEXT ( splitter TEXT )*. splitter will be '%' or
-# an integer.
-_re_subst = re.compile('%(%|[0-9]+)')
-
-class Template:
-
-  def __init__(self, fname=None, compress_whitespace=1):
-    self.compress_whitespace = compress_whitespace
-    if fname:
-      self.parse_file(fname)
-
-  def parse_file(self, fname):
-    "fname -> a string object with pathname of file containg an EZT template."
-
-    self.program = self._parse(_FileReader(fname))
-
-  def parse(self, text_or_reader):
-    """Parse the template specified by text_or_reader.
-
-    The argument should be a string containing the template, or it should
-    specify a subclass of ezt.Reader which can read templates.
-    """
-    if not isinstance(text_or_reader, Reader):
-      # assume the argument is a plain text string
-      text_or_reader = _TextReader(text_or_reader)
-    self.program = self._parse(text_or_reader)
-
-  def generate(self, fp, data):
-    ctx = _context()
-    ctx.data = data
-    ctx.for_index = { }
-    self._execute(self.program, fp, ctx)
-
-  def _parse(self, reader, for_names=None, file_args=()):
-    """text -> string object containing the HTML template.
-
-    This is a private helper function doing the real work for method parse.
-    It returns the parsed template as a 'program'.  This program is a sequence
-    made out of strings or (function, argument) 2-tuples.
-
-    Note: comment directives [# ...] are automatically dropped by _re_parse.
-    """
-
-    # parse the template program into: (TEXT DIRECTIVE BRACKET)* TEXT
-    parts = _re_parse.split(reader.text)
-
-    program = [ ]
-    stack = [ ]
-    if not for_names:
-       for_names = [ ]
-
-    for i in range(len(parts)):
-      piece = parts[i]
-      which = i % 3  # discriminate between: TEXT DIRECTIVE BRACKET
-      if which == 0:
-        # TEXT. append if non-empty.
-        if piece:
-          if self.compress_whitespace:
-            piece = _re_whitespace.sub(' ', _re_newline.sub('\n', piece))
-          program.append(piece)
-      elif which == 2:
-        # BRACKET directive. append '[' if present.
-        if piece:
-          program.append('[')
-      elif piece:
-        # DIRECTIVE is present.
-        args = _re_args.findall(piece)
-        cmd = args[0]
-        if cmd == 'else':
-          if len(args) > 1:
-            raise ArgCountSyntaxError(str(args[1:]))
-          ### check: don't allow for 'for' cmd
-          idx = stack[-1][1]
-          true_section = program[idx:]
-          del program[idx:]
-          stack[-1][3] = true_section
-        elif cmd == 'end':
-          if len(args) > 1:
-            raise ArgCountSyntaxError(str(args[1:]))
-          # note: true-section may be None
-          try:
-            cmd, idx, args, true_section = stack.pop()
-          except IndexError:
-            raise UnmatchedEndError()
-          else_section = program[idx:]
-          func = getattr(self, '_cmd_' + re.sub('-', '_', cmd))
-          program[idx:] = [ (func, (args, true_section, else_section)) ]
-          if cmd == 'for':
-            for_names.pop()
-        elif cmd in _block_cmds:
-          if len(args) > _block_cmd_specs[cmd] + 1:
-            raise ArgCountSyntaxError(str(args[1:]))
-          ### this assumes arg1 is always a ref
-          args[1] = _prepare_ref(args[1], for_names, file_args)
-
-          # handle arg2 for the 'is' command
-          if cmd == 'is':
-            args[2] = _prepare_ref(args[2], for_names, file_args)
-          elif cmd == 'for':
-            for_names.append(args[1][0])
-
-          # remember the cmd, current pos, args, and a section placeholder
-          stack.append([cmd, len(program), args[1:], None])
-        elif cmd == 'include':
-          if args[1][0] == '"':
-            include_filename = args[1][1:-1]
-            f_args = [ ]
-            for arg in args[2:]:
-              f_args.append(_prepare_ref(arg, for_names, file_args))
-            program.extend(self._parse(reader.read_other(include_filename),
-                                       for_names,
-                                       f_args))
-          else:
-            if len(args) != 2:
-              raise ArgCountSyntaxError(str(args))
-            program.append((self._cmd_include,
-                            (_prepare_ref(args[1], for_names, file_args),
-                             reader)))
-        elif cmd == 'if-any':
-          f_args = [ ]
-          for arg in args[1:]:
-            f_args.append(_prepare_ref(arg, for_names, file_args))
-          stack.append(['if-any', len(program), f_args, None])
-        else:
-          # implied PRINT command
-          if len(args) > 1:
-            f_args = [ ]
-            for arg in args:
-              f_args.append(_prepare_ref(arg, for_names, file_args))
-            program.append((self._cmd_format, (f_args[0], f_args[1:])))
-          else:
-            program.append((self._cmd_print,
-                            _prepare_ref(args[0], for_names, file_args)))
-
-    if stack:
-      ### would be nice to say which blocks...
-      raise UnclosedBlocksError()
-    return program
-
-  def _execute(self, program, fp, ctx):
-    """This private helper function takes a 'program' sequence as created
-    by the method '_parse' and executes it step by step.  strings are written
-    to the file object 'fp' and functions are called.
-    """
-    for step in program:
-      if isinstance(step, StringType):
-        fp.write(step)
-      else:
-        step[0](step[1], fp, ctx)
-
-  def _cmd_print(self, valref, fp, ctx):
-    value = _get_value(valref, ctx)
-
-    # if the value has a 'read' attribute, then it is a stream: copy it
-    if hasattr(value, 'read'):
-      while 1:
-        chunk = value.read(16384)
-        if not chunk:
-          break
-        fp.write(chunk)
-    else:
-      fp.write(value)
-
-  def _cmd_format(self, (valref, args), fp, ctx):
-    fmt = _get_value(valref, ctx)
-    parts = _re_subst.split(fmt)
-    for i in range(len(parts)):
-      piece = parts[i]
-      if i%2 == 1 and piece != '%':
-        idx = int(piece)
-        if idx < len(args):
-          piece = _get_value(args[idx], ctx)
-        else:
-          piece = '<undef>'
-      fp.write(piece)
-
-  def _cmd_include(self, (valref, reader), fp, ctx):
-    fname = _get_value(valref, ctx)
-    ### note: we don't have the set of for_names to pass into this parse.
-    ### I don't think there is anything to do but document it.
-    self._execute(self._parse(reader.read_other(fname)), fp, ctx)
-
-  def _cmd_if_any(self, args, fp, ctx):
-    "If any value is a non-empty string or non-empty list, then T else F."
-    (valrefs, t_section, f_section) = args
-    value = 0
-    for valref in valrefs:
-      if _get_value(valref, ctx):
-        value = 1
-        break
-    self._do_if(value, t_section, f_section, fp, ctx)
-
-  def _cmd_if_index(self, args, fp, ctx):
-    ((valref, value), t_section, f_section) = args
-    list, idx = ctx.for_index[valref[0]]
-    if value == 'even':
-      value = idx % 2 == 0
-    elif value == 'odd':
-      value = idx % 2 == 1
-    elif value == 'first':
-      value = idx == 0
-    elif value == 'last':
-      value = idx == len(list)-1
-    else:
-      value = idx == int(value)
-    self._do_if(value, t_section, f_section, fp, ctx)
-
-  def _cmd_is(self, args, fp, ctx):
-    ((left_ref, right_ref), t_section, f_section) = args
-    value = _get_value(right_ref, ctx)
-    value = string.lower(_get_value(left_ref, ctx)) == string.lower(value)
-    self._do_if(value, t_section, f_section, fp, ctx)
-
-  def _do_if(self, value, t_section, f_section, fp, ctx):
-    if t_section is None:
-      t_section = f_section
-      f_section = None
-    if value:
-      section = t_section
-    else:
-      section = f_section
-    if section is not None:
-      self._execute(section, fp, ctx)
-
-  def _cmd_for(self, args, fp, ctx):
-    ((valref,), unused, section) = args
-    list = _get_value(valref, ctx)
-    if isinstance(list, StringType):
-      raise NeedSequenceError()
-    refname = valref[0]
-    ctx.for_index[refname] = idx = [ list, 0 ]
-    for item in list:
-      self._execute(section, fp, ctx)
-      idx[1] = idx[1] + 1
-    del ctx.for_index[refname]
-
-def boolean(value):
-  "Return a value suitable for [if-any bool_var] usage in a template."
-  if value:
-    return 'yes'
-  return None
-
-
-def _prepare_ref(refname, for_names, file_args):
-  """refname -> a string containing a dotted identifier. example:"foo.bar.bang"
-  for_names -> a list of active for sequences.
-
-  Returns a `value reference', a 3-Tupel made out of (refname, start, rest), 
-  for fast access later.
-  """
-  # is the reference a string constant?
-  if refname[0] == '"':
-    return None, refname[1:-1], None
-
-  # if this is an include-argument, then just return the prepared ref
-  if refname[:3] == 'arg':
-    try:
-      idx = int(refname[3:])
-    except ValueError:
-      pass
-    else:
-      if idx < len(file_args):
-        return file_args[idx]
-
-  parts = string.split(refname, '.')
-  start = parts[0]
-  rest = parts[1:]
-  while rest and (start in for_names):
-    # check if the next part is also a "for name"
-    name = start + '.' + rest[0]
-    if name in for_names:
-      start = name
-      del rest[0]
-    else:
-      break
-  return refname, start, rest
-
-def _get_value((refname, start, rest), ctx):
-  """(refname, start, rest) -> a prepared `value reference' (see above).
-  ctx -> an execution context instance.
-
-  Does a name space lookup within the template name space.  Active 
-  for blocks take precedence over data dictionary members with the 
-  same name.
-  """
-  if rest is None:
-    # it was a string constant
-    return start
-  if ctx.for_index.has_key(start):
-    list, idx = ctx.for_index[start]
-    ob = list[idx]
-  elif ctx.data.has_key(start):
-    ob = ctx.data[start]
-  else:
-    raise UnknownReference(refname)
-
-  # walk the rest of the dotted reference
-  for attr in rest:
-    try:
-      ob = getattr(ob, attr)
-    except AttributeError:
-      raise UnknownReference(refname)
-
-  # make sure we return a string instead of some various Python types
-  if isinstance(ob, IntType) or isinstance(ob, FloatType):
-    return str(ob)
-  if ob is None:
-    return ''
-
-  # string or a sequence
-  return ob
-
-
-class _context:
-  """A container for the execution context"""
-
-
-class Reader:
-  "Abstract class which allows EZT to detect Reader objects."
-
-class _FileReader(Reader):
-  """Reads templates from the filesystem."""
-  def __init__(self, fname):
-    self.text = open(fname, 'rb').read()
-    self._dir = os.path.dirname(fname)
-  def read_other(self, relative):
-    return _FileReader(os.path.join(self._dir, relative))
-
-class _TextReader(Reader):
-  """'Reads' a template from provided text."""
-  def __init__(self, text):
-    self.text = text
-  def read_other(self, relative):
-    raise BaseUnavailableError()
-
-
-class EZTException(Exception):
-  """Parent class of all EZT exceptions."""
-
-class ArgCountSyntaxError(EZTException):
-  """A bracket directive got the wrong number of arguments."""
-
-class UnknownReference(EZTException):
-  """The template references an object not contained in the data dictionary."""
-
-class NeedSequenceError(EZTException):
-  """The object dereferenced by the template is no sequence (tuple or list)."""
-
-class UnclosedBlocksError(EZTException):
-  """This error may be simply a missing [end]."""
-
-class UnmatchedEndError(EZTException):
-  """This error may be caused by a misspelled if directive."""
-
-class BaseUnavailableError(EZTException):
-  """Base location is unavailable, which disables includes."""
-
-
-# --- standard test environment ---
-def test_parse():
-  assert _re_parse.split('[a]') == ['', '[a]', None, '']
-  assert _re_parse.split('[a] [b]') == \
-         ['', '[a]', None, ' ', '[b]', None, '']
-  assert _re_parse.split('[a c] [b]') == \
-         ['', '[a c]', None, ' ', '[b]', None, '']
-  assert _re_parse.split('x [a] y [b] z') == \
-         ['x ', '[a]', None, ' y ', '[b]', None, ' z']
-  assert _re_parse.split('[a "b" c "d"]') == \
-         ['', '[a "b" c "d"]', None, '']
-  assert _re_parse.split(r'["a \"b[foo]" c.d f]') == \
-         ['', '["a \\"b[foo]" c.d f]', None, '']
-
-def _test(argv):
-  import doctest, ezt           
-  verbose = "-v" in argv
-  return doctest.testmod(ezt, verbose=verbose)
-
-if __name__ == "__main__":
-  # invoke unit test for this module:
-  import sys
-  sys.exit(_test(sys.argv)[0])

Modified: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/gen_base.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/gen_base.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/gen_base.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 # -*- python -*-
+# -*- condig shift_jis -*-
 #
 #  @file gen_base.py
 #  @brief rtc-template source code generator base class
@@ -13,35 +14,17 @@
 #          Advanced Industrial Science and Technology (AIST), Japan
 #      All rights reserved.
 # 
-#  $Id: gen_base.py,v 1.4 2007/01/11 07:43:16 n-ando Exp $
+#  $Id: gen_base.py 775 2008-07-28 16:14:45Z n-ando $
 # 
 
-#
-#  $Log: gen_base.py,v $
-#  Revision 1.4  2007/01/11 07:43:16  n-ando
-#  A trivial fix.
-#
-#  Revision 1.3  2005/09/08 09:24:06  n-ando
-#  - A bug fix for merge function.
-#
-#  Revision 1.2  2005/09/06 14:37:29  n-ando
-#  rtc-template's command options and data structure for ezt (Easy Template)
-#  are changed for RTComponent's service features.
-#  Now rtc-template can generate services' skeletons, stubs and
-#  implementation files.
-#  The implementation code generation uses omniidl's IDL parser.
-#
-#
-
 import os
 import re
 import time
-import ezt
+import yat
 import StringIO
-
 class gen_base:
 	
-	def check_overwrite(self, fname):
+	def check_overwrite(self, fname, wmode="w"):
 		"""
 		Check file exist or not.
 		"""
@@ -49,7 +32,7 @@
 		if (os.access(fname, os.F_OK)):
 			ans = raw_input("\"" + fname + "\"" + msg)
 			if (ans == "y" or ans == "Y"):
-				return file(fname, "w"), None
+				return file(fname, wmode), None
 			elif (ans == "m" or ans == "M"):
 				f = file(fname, "r")
 				lines = []
@@ -58,11 +41,11 @@
 				f.close()
 				oldfname = fname + ".old." + time.strftime("%y%m%d%H%M%S")
 				os.rename(fname, oldfname)
-				return file(fname, "w"), lines
+				return file(fname, wmode), lines
 			else:
 				return None, None
 		else:
-			return file(fname, "w"), None
+			return file(fname, wmode), None
 		return
 	
 	def replace_tags(self, lines, data):
@@ -95,11 +78,9 @@
 
 	def gen_tags(self, tags):
 		for key in tags.keys():
-			s = StringIO.StringIO()
-			t = ezt.Template(compress_whitespace = 0)
-			t.parse(tags[key])
-			t.generate(s, self.data)
-			tags[key] = s.getvalue()
+			t = yat.Template(tags[key])
+			text=t.generate(self.data)
+			tags[key] = text
 		return
 
 	def gen(self, fname, temp_txt, data, tags):
@@ -108,33 +89,14 @@
 			return
 
 		if not lines:  # overwrite: Yes
-			s = StringIO.StringIO()
-			t = ezt.Template(compress_whitespace = 0)
-			t.parse(temp_txt)
-			t.generate(s, data)
-			taged_txt = s.getvalue().splitlines()
+			t = yat.Template(temp_txt)
+			taged_txt = t.generate(self.data)
 		else:          # overwrite: Merge mode
 			taged_txt = lines
 
 		# replace tags
-		gen_txt = self.replace_tags(taged_txt, tags)
+		gen_txt = self.replace_tags(taged_txt.split("\n"), tags)
 		f.write(gen_txt)
 		f.close()
 		print "  File \"" + fname + "\"" " was generated."
 		return
-		
-
-
-if __name__ == "__main__":
-	hoge = """
- protected:
-  // <rtc-template block="inport_declar">
-  // </rtc-template>
-
-  // <rtc-template block="outport_declar">
-  // </rtc-template>
-"""
-	data = {"inport_declar": "  hoge;\n  dara;\n  munya;",
-			"outport_declar": "  1;\n  2;\n  3;"}
-	g = gen_base()
-	print g.replace_tags(hoge.splitlines(), data)

Copied: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/profile_gen.py (from rev 495, branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/profile_gen.py)
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/profile_gen.py	                        (rev 0)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/profile_gen.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -0,0 +1,352 @@
+#!/usr/bin/env python
+# -*- python -*-
+#
+#  @file profile_gen.py
+#  @brief RTC profile generator
+#  @date $Date$
+#  @author Noriaki Ando <n-ando at aist.go.jp>
+# 
+#  Copyright (C) 2008
+#      Task-intelligence Research Group,
+#      Intelligent Systems Research Institute,
+#      National Institute of
+#          Advanced Industrial Science and Technology (AIST), Japan
+#      All rights reserved.
+# 
+#  $Id$
+#
+
+import gen_base
+
+profile_yaml = """rtcProfile: 
+  version: "1.0"
+  id: [id]
+
+  basicInfo:
+    name: [basicInfo.name]
+
+    description: [basicInfo.description]
+
+    version: [basicInfo.version]
+
+    vendor: [basicInfo.vendor]
+
+    category: [basicInfo.category]
+
+    componentType: [basicInfo.componentType]
+
+    activityType: [basicInfo.activityType]
+
+    componentKind: [basicInfo.componentKind]
+
+    maxInstances: [basicInfo.maxInstances]
+
+    abstract: [basicInfo.abstract]
+
+    executionRate: [basicInfo.executionRate]
+
+    executionType: [basicInfo.executionType]
+
+    creationDate:
+      year: [basicInfo.creationDate.year]
+
+      month: [basicInfo.creationDate.month]
+
+      day: [basicInfo.creationDate.day]
+
+      hour: [basicInfo.creationDate.hour]
+
+      minute: [basicInfo.creationDate.minute]
+
+      second: [basicInfo.creationDate.second]
+
+    updateDate:
+      year: [basicInfo.updateDate.year]
+
+      month: [basicInfo.updateDate.month]
+
+      day: [basicInfo.updateDate.day]
+
+      hour: [basicInfo.updateDate.hour]
+
+      minute: [basicInfo.updateDate.minute]
+
+      second: [basicInfo.updateDate.second]
+
+    "rtcDoc::doc":
+      algorithm: [basicInfo.rtcDoc::doc.algorithm]
+
+      creator: [basicInfo.rtcDoc::doc.creator]
+
+      description: [basicInfo.rtcDoc::doc.description]
+
+      inout: [basicInfo.rtcDoc::doc.inout]
+
+      license: [basicInfo.rtcDoc::doc.license]
+
+      reference: [basicInfo.rtcDoc::doc.reference]
+
+    "rtcExt::versionUpLog": 
+[for log in basicInfo.rtcExt::versionUpLog]
+      - [log]
+[endfor]
+  language: 
+[if-any language.java]
+    java: 
+      library: 
+[for javalib in language.java.library]
+        - [javalib]
+[endfor]
+[endif]
+  actions:  
+    onInitialize:
+      implemented: [actions.onInitialize.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onInitialize.rtcDoc::doc.description]
+
+        postCondition: [actions.onInitialize.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onInitialize.rtcDoc::doc.preCondition]
+
+    onActivated:
+      implemented: [actions.onActivated.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onActivated.rtcDoc::doc.description]
+
+        postCondition: [actions.onActivated.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onActivated.rtcDoc::doc.preCondition]
+
+    onDeactivated:
+      implemented: [actions.onDeactivated.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onDeactivated.rtcDoc::doc.description]
+
+        postCondition: [actions.onDeactivated.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onDeactivated.rtcDoc::doc.preCondition]
+
+    onAborting:
+      implemented: [actions.onAborting.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onAborting.rtcDoc::doc.description]
+
+        postCondition: [actions.onAborting.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onAborting.rtcDoc::doc.preCondition]
+
+    onError:
+      implemented: [actions.onError.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onError.rtcDoc::doc.description]
+
+        postCondition: [actions.onError.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onError.rtcDoc::doc.preCondition]
+
+    onReset:
+      implemented: [actions.onReset.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onReset.rtcDoc::doc.description]
+
+        postCondition: [actions.onReset.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onReset.rtcDoc::doc.preCondition]
+
+    onFinalize:
+      implemented: [actions.onFinalize.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onFinalize.rtcDoc::doc.description]
+
+        postCondition: [actions.onFinalize.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onFinalize.rtcDoc::doc.preCondition]
+
+    onStartup:
+      implemented: [actions.onStartup.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onStartup.rtcDoc::doc.description]
+
+        postCondition: [actions.onStartup.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onStartup.rtcDoc::doc.preCondition]
+
+    onRateChanged:
+      implemented: [actions.onRateChanged.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onRateChanged.rtcDoc::doc.description]
+
+        postCondition: [actions.onRateChanged.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onRateChanged.rtcDoc::doc.preCondition]
+
+    onShutdown:
+      implemented: [actions.onShutdown.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onShutdown.rtcDoc::doc.description]
+
+        postCondition: [actions.onShutdown.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onShutdown.rtcDoc::doc.preCondition]
+
+    onExecute:
+      implemented: [actions.onExecute.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onExecute.rtcDoc::doc.description]
+
+        postCondition: [actions.onExecute.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onExecute.rtcDoc::doc.preCondition]
+
+    onStateUpdate:
+      implemented: [actions.onStateUpdate.implemented]
+
+      "rtcDoc::doc":
+        description: [actions.onStateUpdate.rtcDoc::doc.description]
+
+        postCondition: [actions.onStateUpdate.rtcDoc::doc.postCondition]
+
+        preCondition: [actions.onStateUpdate.rtcDoc::doc.preCondition]
+
+  dataPorts: 
+[for dport in dataPorts]
+    -
+      portType: [dport.portType]
+
+      name: [dport.name]
+
+      type: [dport.type]
+
+      interfaceType: [dport.interfaceType]
+
+      dataflowType: [dport.dataflowType]
+
+      subscriptionType: [dport.subscriptionType]
+
+      idlFile: [dport.idlFile]
+
+      "rtcDoc::doc":
+        type: [dport.rtcDoc::doc.type]
+
+        description: [dport.rtcDoc::doc.description]
+
+        number: [dport.rtcDoc::doc.number]
+
+        occerrence: [dport.rtcDoc::doc.occerrence]
+
+        operation: [dport.rtcDoc::doc.operation]
+
+        semantics: [dport.rtcDoc::doc.semantics]
+
+        unit: [dport.rtcDoc::doc.unit]
+
+      "rtcExt::position": [dport.rtcExt::position]
+
+      "rtcExt::varname": [dport.rtcExt::varname]
+
+[endfor]
+  servicePorts: 
+[for sport in servicePorts]
+    -
+      name: [sport.name]
+
+      "rtcDoc::doc":
+        description: [sport.rtcDoc::doc.description]
+
+        ifdescription: [sport.rtcDoc::doc.ifdescription]
+
+      "rtcExt::position": [sport.rtcExt::position]
+
+      serviceInterface: 
+[for sif in sport.serviceInterface]
+        -
+          direction: [sif.direction]
+
+          name: [sif.name]
+
+          type: [sif.type]
+
+          varname: [sif.varname]
+
+          instanceName: [sif.instanceName]
+
+          idlFile: [sif.idlFile]
+
+          path: [sif.path]
+
+          "rtcDoc::doc":
+            description: [sif.rtcDoc::doc.description]
+
+            docArgument: [sif.rtcDoc::doc.docArgument]
+
+            docException: [sif.rtcDoc::doc.docException]
+
+            docPostCondition: [sif.rtcDoc::doc.docPostCondition]
+
+            docPreCondition: [sif.rtcDoc::doc.docPreCondition]
+
+            docReturn: [sif.rtcDoc::doc.docReturn]
+
+[endfor]
+[endfor]
+  configurationSet: 
+    configuration: 
+[for conf in configurationSet.configuration]
+      - 
+        name: [conf.name]
+
+        type: [conf.type]
+
+        varname: [conf.varname]
+
+        defaultValue: [conf.defaultValue]
+
+        "rtcDoc::doc":
+          constraint: [conf.rtcDoc::doc.constraint]
+
+          dataname: [conf.rtcDoc::doc.dataname]
+
+          defaultValue: [conf.rtcDoc::doc.defaultValue]
+
+          description: [conf.rtcDoc::doc.description]
+
+          range: [conf.rtcDoc::doc.range]
+
+          unit: [conf.rtcDoc::doc.unit]
+
+[endfor]
+  parameters: 
+[if-any parameters]
+[for param in parameters]
+    -
+      name: [param.name]
+
+      defaultValue: [param.defaultValue]
+
+[endfor]
+[endif]
+"""
+
+
+class profile_gen(gen_base.gen_base):
+    def __init__(self, data):
+        self.data = data
+        self.data["fname"] = data["basicInfo"]["name"] + ".yaml"
+        self.tags = {}
+
+    def print_yamlprofile(self):
+        self.gen(self.data["fname"], profile_yaml, self.data, self.tags)
+
+    def print_all(self):
+        self.print_yamlprofile()

Modified: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/python_gen.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/python_gen.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/python_gen.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,36 +1,24 @@
 #!/usr/bin/env python
-# -*- coding: utf-8 -*-
+# -*- Python -*-
 #
 #  @file Py_src.py
 #  @brief rtc-template Python soruce code generator class
 #  @date $Date: 2005/08/26 12:02:37 $
 #  @author Noriaki Ando <n-ando at aist.go.jp>
 # 
-#  Copyright (C) 2004-2005
+#  Copyright (C) 2004-2008
 #      Task-intelligence Research Group,
 #      Intelligent Systems Research Institute,
 #      National Institute of
 #          Advanced Industrial Science and Technology (AIST), Japan
 #      All rights reserved.
 # 
-#  $Id: python_gen.py,v 1.1 2005/08/26 12:02:37 n-ando Exp $
+#  $Id: python_gen.py 775 2008-07-28 16:14:45Z n-ando $
 # 
 
-#
-#  $Log: python_gen.py,v $
-#  Revision 1.1  2005/08/26 12:02:37  n-ando
-#  This code generator module uses ezt (Easy Template).
-#
-#  Revision 1.1.1.1  2005/05/12 09:06:18  n-ando
-#  Public release.
-#
-#
-
 import re
 import os
-import ezt
 import gen_base
-
 import string
 import sys
 
@@ -56,33 +44,79 @@
 def get_opt_fmt():
   return []
 
-
 service_impl = """\
-[for service_idl]from [service_idl.idl_basename]_idl_example import *
-[end]"""
+[for sidl in service_idl]
+from [sidl.idl_basename]_idl_example import *
+[endfor]"""
 
-consumer_import = """\
+global_idl = """\
 import _GlobalIDL, _GlobalIDL__POA
 """
+no_global_idl = ""
 
-initialize_configuration_param = """\
-    [for config]self._[config.name] = [config.default_data]
-    [end]"""
-
 module_spec = """\
-[l_name]_spec = ["implementation_id", "[module.name]", 
-     "type_name",         "[module.name]", 
-     "description",       "[module.desc]", 
-     "version",           "[module.version]", 
-     "vendor",            "[module.vendor]", 
-     "category",          "[module.category]", 
-     "activity_type",     "[module.comp_type]", 
-     "max_instance",      "[module.max_inst]", 
-     "language",          "Python", 
-     "lang_type",         "SCRIPT",
-[for config]     "conf.default.[config.name]", "[config.default]",
-[end]    ""]"""
+[l_name]_spec = ["implementation_id", "[basicInfo.name]", 
+		 "type_name",         "[basicInfo.name]", 
+		 "description",       "[basicInfo.description]", 
+		 "version",           "[basicInfo.version]", 
+		 "vendor",            "[basicInfo.vendor]", 
+		 "category",          "[basicInfo.category]", 
+		 "activity_type",     "[basicInfo.componentType]", 
+		 "max_instance",      "[basicInfo.maxInstances]", 
+		 "language",          "Python", 
+		 "lang_type",         "SCRIPT",
+[if-any configurationSet.configuration]
+[for config in configurationSet.configuration]
+		 "conf.default.[config.name]", "[config.defaultValue]",
+[endfor][endif]
+		 ""]
+"""
 
+data_ports = """\
+[for dport in dataPorts]
+    self._d_[dport.name] = RTC.[dport.type]([dport.data_type_args])
+[if dport.portType is DataInPort]
+    self._[dport.name]In = OpenRTM_aist.InPort("[dport.name]", self._d_[dport.name])
+    self.addInPort("[dport.name]",self._[dport.name]In)
+
+[elif dport.portType is DataOutPort]
+    self._[dport.name]Out = OpenRTM_aist.OutPort("[dport.name]", self._d_[dport.name])
+    self.addOutPort("[dport.name]",self._[dport.name]Out)
+
+[endif]
+[endfor]
+"""
+
+service_ports = """\
+[for sport in servicePorts]
+    self._[sport.name]Port = OpenRTM_aist.CorbaPort("[sport.name]")
+[for sif in sport.serviceInterface]
+[if sif.direction is Provided]
+    self._[sif.name] = [sif.type]_i()
+    self._[sport.name]Port.registerProvider("[sif.name]", "[sif.type]", self._[sif.name])
+[elif sif.direction is Required]
+    self._[sif.name] = OpenRTM_aist.CorbaConsumer(interfaceType=_GlobalIDL.[sif.type])
+    self._[sport.name]Port.registerConsumer("[sif.name]", "[sif.type]", self._[sif.name])
+[endif]
+    self.addPort(self._[sport.name]Port)
+
+[endfor]
+[endfor]
+"""
+
+configurations = """\
+[for config in configurationSet.configuration]
+    self._[config.name] = [config.defaultData]
+
+[endfor]
+"""
+
+bind_config = """
+[for conf in configurationSet.configuration]
+    self.bindParameter("[conf.name]", self._[conf.name], "[conf.defaultValue]")
+[endfor]"""
+
+
 #------------------------------------------------------------
 # Python component source code template
 #------------------------------------------------------------
@@ -90,7 +124,6 @@
 # -*- Python -*-
 
 import sys
-import time
 sys.path.append(".")
 
 # Import RTM module
@@ -102,7 +135,7 @@
 # </rtc-template>
 
 # Import Service stub modules
-# <rtc-template block="consumer_import">
+# <rtc-template block="global_idl">
 # </rtc-template>
 
 
@@ -110,70 +143,49 @@
 # <rtc-template block="module_spec">
 # </rtc-template>
 
-class [module.name](OpenRTM_aist.DataFlowComponentBase):
+class [basicInfo.name](OpenRTM_aist.DataFlowComponentBase):
   def __init__(self, manager):
     OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)
 
-    [for inport]self._d_[inport.name] = RTC.[inport.type]([inport.data_type_args])
-    self._[inport.name]In = OpenRTM_aist.InPort("[inport.name]", self._d_[inport.name])
-    [end][for outport]self._d_[outport.name] = RTC.[outport.type]([outport.data_type_args])
-    self._[outport.name]Out = OpenRTM_aist.OutPort("[outport.name]", self._d_[outport.name])
-    [end]
-    [for corbaport]self._[corbaport.name]Port = OpenRTM_aist.CorbaPort("[corbaport.name]")
-    [end]
-    [for service]self._[service.name] = [service.type]_i()
-    [end]
-    [for consumer]self._[consumer.name] = OpenRTM_aist.CorbaConsumer(interfaceType=_GlobalIDL.[consumer.type])
-    [end]
     # initialize of configuration-data.
-    # <rtc-template block="init_conf_param">
+    # <rtc-template block="configurations">
     # </rtc-template>
 
 
-     
   def onInitialize(self):
-    # Bind variables and configuration variable
-    [for config]self.bindParameter("[config.name]", self._[config.name], "[config.default]")
-    [end]
+    # DataPorts initialization
+    # <rtc-template block="data_ports">
+    # </rtc-template>
 
-    # Set InPort buffers
-    [for inport]self.addInPort("[inport.name]",self._[inport.name]In)
-    [end]
-    # Set OutPort buffers
-    [for outport]self.addOutPort("[outport.name]",self._[outport.name]Out)
-    [end]
+    # ServicePorts initialization
+    # <rtc-template block="service_ports">
+    # </rtc-template>
 
-    # Set service provider to Ports
-    [for service]self._[service.port]Port.registerProvider("[service.name]", "[service.type]", self._[service.name])
-    [end]
-    # Set service consumers to Ports
-    [for consumer]self._[consumer.port]Port.registerConsumer("[consumer.name]", "[consumer.type]", self._[consumer.name])
-    [end]
-    # Set CORBA Service Ports
-    [for corbaport]self.addPort(self._[corbaport.name]Port)
-    [end]
-
+    # Bind variables and configuration variable
+    # <rtc-template block="bind_config">
+    # </rtc-template>
     return RTC.RTC_OK
 
 
-  [for activity]
-  #def [activity.name](self, ec_id):
-  #
-  # return RTC.RTC_OK
-  [end]
+[for act in activity]
+  #def [act.name](self[if-any act.args], [act.args][else][endif]):
+  #  return RTC.RTC_OK
 
+[endfor]
 
-def [module.name]Init(manager):
+
+def [basicInfo.name]Init(manager):
   profile = OpenRTM_aist.Properties(defaults_str=[l_name]_spec)
   manager.registerFactory(profile,
-                          [module.name],
+                          [basicInfo.name],
                           OpenRTM_aist.Delete)
 
+
 def MyModuleInit(manager):
-  [module.name]Init(manager)
+  [basicInfo.name]Init(manager)
 
   # Create a component
-  comp = manager.createComponent("[module.name]")
+  comp = manager.createComponent("[basicInfo.name]")
 
 
 
@@ -190,138 +202,128 @@
 
 
 
-class Struct:
-  def __init__(self):
-    return
 
-
-def MakeActivityFuncs(dict):
-  acts = (("onFinalize",    ""), \
-    ("onStartup",     "RTC::UniqueId ec_id"), \
-    ("onShutdown",    "RTC::UniqueId ec_id"), \
-    ("onActivated",   "RTC::UniqueId ec_id"), \
-    ("onDeactivated", "RTC::UniqueId ec_id"), \
-    ("onExecute",     "RTC::UniqueId ec_id"), \
-    ("onAborting",    "RTC::UniqueId ec_id"), \
-    ("onError",       "RTC::UniqueId ec_id"), \
-    ("onReset",       "RTC::UniqueId ec_id"), \
-    ("onStateUpdate", "RTC::UniqueId ec_id"), \
-    ("onRateChanged", "RTC::UniqueId ec_id"))
-  actlist = []
-  for name, args in acts:
-    a = Struct()
-    a.name = name
-    a.args = args
-    actlist.append(a)
-
-  dict["activity"] = actlist
-
-
-def MakeSuffix(opts, dict):
-  impl_suffix = "SVC_impl"
-  skel_suffix = "Skel"
-  stub_suffix = "Stub"
-  for opt, arg in opts:
-    if opt.find("--svc-impl-suffix") == 0:
-      impl_suffix = arg
-    if opt.find("--svc-skel-suffix") == 0:
-      skel_suffix = arg
-    if opt.find("--svc-stub-suffix") == 0:
-      stub_suffix = arg
-  dict["impl_suffix"] = impl_suffix
-  dict["skel_suffix"] = skel_suffix
-  dict["stub_suffix"] = stub_suffix
-  
-
 class python_gen(gen_base.gen_base):
   """
   Python component source code generation class
   """
   def __init__(self, data, opts):
-    self.data = data.copy()
-    MakeActivityFuncs(self.data)
-    MakeSuffix(opts, self.data)
+    self.data = data
+    self.data['fname'] = self.data['basicInfo']['name']
     self.data['fname_py'] = self.data['fname'] + ".py"
-    self.data["begin_brace"] = "["
-    self.data["end_brace"] = "]"
-    self.data["u_name"] = self.data["module"].name.upper()
-    self.data["l_name"] = self.data["module"].name.lower()
+    self.data["u_name"] = self.data["fname"].upper()
+    self.data["l_name"] = self.data["fname"].lower()
 
-
+    self.CreateActivityFuncs(self.data)
+    self.CreateDataPorts(self.data)
+    self.CreateService(self.data)
+    self.CreateConfiguration(self.data)
     self.tags = {}
-    if self.data["service_idl"]:
-      for svc in self.data["service_idl"]:
-        svc.impl_py = svc.idl_basename + "_idl_example.py"
-      self.tags["service_impl"]    = service_impl
+    self.tags["service_impl"]    = service_impl
+    if len(self.data["service_idl"]) > 0 or \
+          len(self.data["consumer_idl"]) > 0:
+      self.tags["global_idl"] = global_idl
+    else:
+      self.tags["global_idl"] = no_global_idl
+    self.tags["module_spec"]     = module_spec
+    self.tags["data_ports"]      = data_ports
+    self.tags["service_ports"]   = service_ports
+    self.tags["configurations"]  = configurations
+    self.tags["bind_config"]     = bind_config
+    self.gen_tags(self.tags)
+    return
 
-    if self.data["consumer_idl"]:
-      for cons in self.data["consumer_idl"]:
+
+  def CreateActivityFuncs(self, dict):
+    acts = (("onFinalize",    None), \
+              ("onStartup",     "ec_id"), \
+              ("onShutdown",    "ec_id"), \
+              ("onActivated",   "ec_id"), \
+              ("onDeactivated", "ec_id"), \
+              ("onExecute",     "ec_id"), \
+              ("onAborting",    "ec_id"), \
+              ("onError",       "ec_id"), \
+              ("onReset",       "ec_id"), \
+              ("onStateUpdate", "ec_id"), \
+              ("onRateChanged", "ec_id"))
+    actlist = []
+    for name, args in acts:
+      a = {}
+      a["name"] = name
+      a["args"] = args
+      actlist.append(a)
+	
+    dict["activity"] = actlist
+    return
+	
+  def CreateService(self, dict):
+    if dict["service_idl"]:
+      for svc in dict["service_idl"]:
+        svc["impl_py"] = svc["idl_basename"] + \
+            "_idl_example.py"
+			
+    if dict["consumer_idl"]:
+      for cons in dict["consumer_idl"]:
         try:
-          cons.modulename = "_GlobalIDL"
-          f = open(cons.idl_fname,'a+')
+          cons["modulename"] = "_GlobalIDL"
+          f = open(cons["idl_fname"], 'a+')
           while 1:
             _str = f.readline()
             if not _str:
               break
-            mod_idx = _str.find("module",0)
-            if mod_idx > -1:
-              _str = _str[mod_idx+6:]
-              idx = _str.find("{",0)
-              if idx > -1:
-                _str = _str[:idx]
-              cons.modulename = string.strip(_str)
+            mod_idx = _str.find("module", 0)
+            if mod_idx < 0:
+              break;
+            _str = _str[mod_idx + 6:]
+            idx = _str.find("{", 0)
+            if idx < 0:
               break
+            _str = _str[:idx]
+            cons["modulename"] = \
+                string.strip(_str)
+            break
           f.close()
         except IOError:
           print "Can't find file:", file
+    return
 
-      self.tags["consumer_import"] = consumer_import
-        
-    if self.data["config"]:
-      for i in range(len(self.data["config"])):
-        split_data = self.data["config"][i].default.split(",")
+  def CreateDataPorts(self, dict):
+    if dict["dataPorts"] == None:
+      return
+    for dport in dict["dataPorts"]:
+      if self.check_data_type(dport["type"]) == "sequence":
+        dport["data_type_args"] = "RTC.Time(0,0),[]"
+      else:
+        dport["data_type_args"] = "RTC.Time(0,0),0"
+    return
+	
+  def CreateConfiguration(self, dict):
+    config = dict["configurationSet"]["configuration"]
+    if config:
+      for i, conf in enumerate(config):
+        split_data = conf["defaultValue"].split(",")
         if len(split_data) > 1:
           _data = []
-          _type = self.get_type(self.data["config"][i].type)
+          _type = self.get_type(conf["type"])
           for d in split_data:
             _data.append(_type(d))
-          self.data["config"][i].default_data = [_data]
+          conf["defaultData"] = str([_data])
         else:
-          _type = self.get_type(self.data["config"][i].type)
-          self.data["config"][i].default_data = [_type(self.data["config"][i].default)]
-        
-    self.tags["init_conf_param"] = initialize_configuration_param
-
-    if self.data["inport"]:
-      for inp in self.data["inport"]:
-        if self.check_data_type(inp.type) == "sequence":
-          inp.data_type_args = "RTC.Time(0,0),[]"
-        else:
-          inp.data_type_args = "RTC.Time(0,0),0"
-
-    if self.data["outport"]:
-      for outp in self.data["outport"]:
-        if self.check_data_type(outp.type) == "sequence":
-          outp.data_type_args = "RTC.Time(0,0),[]"
-        else:
-          outp.data_type_args = "RTC.Time(0,0),0"
-
-
-      
-    self.tags["module_spec"]       = module_spec
-    self.gen_tags(self.tags)
+          _type = self.get_type(conf["type"])
+          conf["defaultData"] = \
+              str([_type(conf["defaultValue"])])
     return
 
-
   def check_data_type(self, _type):
-    if str(_type) in ["TimedShortSeq", "TimedLongSeq", "TimedUShortSeq",
-          "TimedULongSeq", "TimedFloatSeq", "TimedDoubleSeq",
-          "TimedCharSeq","TimedBooleanSeq", "TimedOctetSeq",
-          "TimedStringSeq"]:
+    if str(_type) in ["TimedShortSeq", "TimedLongSeq",
+                      "TimedUShortSeq", "TimedULongSeq",
+                      "TimedFloatSeq", "TimedDoubleSeq",
+                      "TimedCharSeq","TimedBooleanSeq",
+                      "TimedOctetSeq", "TimedStringSeq"]:
       return "sequence"
     else:
       return None
-       
+    return None
 
   def get_type(self, _type):
     if str(_type) == "int":
@@ -336,53 +338,55 @@
       return str
     else:
       return str
-    
 
+    return str
+		
   def print_impl(self):
-    for svc_idl in self.data["service_idl"]:
-      if not os.access(svc_idl.idl_fname, os.F_OK):
+    for sidl in self.data["service_idl"]:
+      if not os.access(sidl["idl_fname"], os.F_OK):
         sys.stderr.write("Error: IDL file \"" \
-             + svc_idl.idl_fname \
-             + "\" not found.\n")
+                           + sidl["idl_fname"] \
+                           + "\" not found.\n")
         sys.exit(1)
-
+          
       try:
-        cmd = "omniidl -bpython -Wbexample "+svc_idl.idl_fname
+        cmd = "omniidl -bpython -Wbexample " + \
+            sidl["idl_fname"]
         os.system(cmd)
       except:
         sys.stderr.write("Generate error: " \
-             + svc_idl.impl_py + "\n")
-
-
+                           + sidl["impl_py"] + "\n")
+        
       print "  File \"" \
-            + svc_idl.impl_py \
-            + "\" was generated."
+          + sidl["impl_py"] \
+          + "\" was generated."
 
     for cons in self.data["consumer_idl"]:
       dup = False
       for svc in self.data["service_idl"]:
-        if cons.idl_fname == svc.idl_fname:
+        if cons["idl_fname"] == svc["idl_fname"]:
           dup = True
 
       if not dup:
-        if not os.access(cons.idl_fname, os.F_OK):
+        if not os.access(cons["idl_fname"], os.F_OK):
           sys.stderr.write("Error: IDL file \"" \
-               + cons.idl_fname \
-               + "\" not found.\n")
+                             + cons["idl_fname"] \
+                             + "\" not found.\n")
           sys.exit(1)
 
         try:
-          cmd = "omniidl -bpython "+cons.idl_fname
+          cmd = "omniidl -bpython " + \
+              cons["idl_fname"]
           os.system(cmd)
         except:
-          sys.stderr.write("Generate error: omniidl -bpython "+cons.idl_fname)
+          sys.stderr.write("Generate error: omniidl -bpython " + cons["idl_fname"])
+    return
 
-
   def print_pysrc(self):
     """
     Generate component class script
     """
-    self.gen(self.data["fname_py"],py_source,self.data, self.tags)
+    self.gen(self.data["fname_py"], py_source, self.data, self.tags)
     return
 
 

Modified: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/rtc-template.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/rtc-template.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/rtc-template.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,116 +1,241 @@
 #!/usr/bin/env python
-# -*- python -*-
+# -*- Python -*-
 #
 #  @file rtc-template
 #  @brief rtc-template RTComponent source code generator tool
-#  @date $Date: 2007/07/23 08:06:27 $
+#  @date $Date: 2007-10-09 07:19:15 $
 #  @author Noriaki Ando <n-ando at aist.go.jp>
 # 
-#  Copyright (C) 2004-2007
+#  Copyright (C) 2004-2008
 #      Task-intelligence Research Group,
 #      Intelligent Systems Research Institute,
 #      National Institute of
 #          Advanced Industrial Science and Technology (AIST), Japan
 #      All rights reserved.
 # 
-#  $Id: rtc-template,v 1.8.2.2 2007/07/23 08:06:27 n-ando Exp $
+#  $Id: rtc-template 1815 2010-01-27 20:26:57Z n-ando $
 #
 
-#
-#  $Log: rtc-template,v $
-#  Revision 1.8.2.2  2007/07/23 08:06:27  n-ando
-#  Modified for win32 porting about rtm-config.
-#
-#  Revision 1.8.2.1  2007/07/20 17:29:03  n-ando
-#  A fix for win32 porting.
-#
-#  Revision 1.8  2007/04/27 00:56:35  n-ando
-#  Example shown in help message was modified for new version.
-#
-#  Revision 1.7  2007/04/23 07:31:28  n-ando
-#  Now "--conf" option can accept scope resolution operator of C++.
-#
-#  Revision 1.6  2007/04/23 01:41:21  n-ando
-#  New option "--config" and configuration template code were added.
-#
-#  Revision 1.5  2007/01/11 07:42:25  n-ando
-#  Modified for OMG RTC specificatin and OpenRTM-aist-0.4.0
-#  - Some command option was chaged and removed.
-#  - Now empty Struct class is used instead of *Profile classes for ezt dict.
-#  - Some bugs were fixed.
-#
-#  Revision 1.4  2005/09/08 09:24:18  n-ando
-#  - A bug fix for merge function.
-#
-#  Revision 1.3  2005/09/06 14:37:40  n-ando
-#  rtc-template's command options and data structure for ezt (Easy Template)
-#  are changed for RTComponent's service features.
-#  Now rtc-template can generate services' skeletons, stubs and
-#  implementation files.
-#  The implementation code generation uses omniidl's IDL parser.
-#
-#  Revision 1.2  2005/08/26 11:32:26  n-ando
-#  "rtc-template" was completely rewritten to use ezt (Easy Template) module.
-#  "ezt" module is originally included in "Subversion".
-#
-#  Now template code generator modules, which are named xxx_gen.py, are
-#  automatically imported from rtc-template, and command options and help
-#  menu are automatically generated.
-#
-#  New template code generator has to inherit base_gen class in
-#  "base_gen.py" module to utilize this framework.
-#
-#  Revision 1.1.1.1  2005/05/12 09:06:18  n-ando
-#  Public release.
-#
-#
-
 import getopt, sys
+import time
 import re
 import os
+import yaml
+import copy
 
-platform = sys.platform
+from distutils.sysconfig import get_python_lib
 
+default_profile="""
+rtcProfile: 
+  version: "1.0"
+  id: # RTC:SampleVendor.SampleCategory.SampleComponent:1.0.0
+  basicInfo:
+    name: ""
+    description: ""
+    version: 1.0.0
+    vendor: SampleVendor
+    category: ""
+    componentType: STATIC
+    activityType: PERIODIC
+    componentKind: DataFlowComponent
+    maxInstances: 1
+    abstract: ""
+    executionRate: 1000.0
+    executionType: PeriodicExecutionContext
+    creationDate:
+      day: ""
+      hour: ""
+      minute: ""
+      month: ""
+      second: ""
+      year: ""
+    updateDate:
+      day: 17
+      hour: 14
+      minute: 0
+      month: 4
+      second: 0
+      year: 2008
+    "rtcDoc::doc":
+      algorithm: ""
+      creator: ""
+      description: ""
+      inout: ""
+      license: ""
+      reference: ""
+    "rtcExt::versionUpLog": 
+      - "2008/04/18 14:00:00:Ver1.0"
+      - "2008/04/18 17:00:00:Ver1.1"
+  language: 
+    java: 
+      library: 
+        - library1
+  actions: 
+    onAborting:
+      "rtcDoc::doc":
+        description: on_aborting description
+        postCondition: on_aborting Post_condition
+        preCondition: on_aborting Pre_condition
+      implemented: true
+    onActivated:
+      "rtcDoc::doc":
+        description: on_activated description
+        postCondition: on_activated Post_condition
+        preCondition: on_activated Pre_condition
+      implemented: true
+    onDeactivated:
+      "rtcDoc::doc":
+        description: on_deactivated description
+        postCondition: on_deactivated Post_condition
+        preCondition: on_deactivated Pre_condition
+    onError:
+      "rtcDoc::doc":
+        description: on_error description
+        postCondition: on_error Post_condition
+        preCondition: on_error Pre_condition
+    onExecute:
+      "rtcDoc::doc":
+        description: on_execute description
+        postCondition: on_execute Post_condition
+        preCondition: on_execute Pre_condition
+    onFinalize:
+      "rtcDoc::doc":
+        description: on_finalize description
+        postCondition: on_finalize Post_condition
+        preCondition: on_finalize Pre_condition
+    onInitialize:
+      "rtcDoc::doc":
+        description: on_initialize description
+        postCondition: on_initialize Post_condition
+        preCondition: on_initialize Pre_condition
+      implemented: true
+    onRateChanged:
+      "rtcDoc::doc":
+        description: on_rate_changed description
+        postCondition: on_rate_changed Post_condition
+        preCondition: on_rate_changed Pre_condition
+    onReset:
+      "rtcDoc::doc":
+        description: on_reset description
+        postCondition: on_reset Post_condition
+        preCondition: on_reset Pre_condition
+    onShutdown:
+      "rtcDoc::doc":
+        description: on_shutdown description
+        postCondition: on_shutdown Post_condition
+        preCondition: on_shutdown Pre_condition
+      implemented: true
+    onStartup:
+      "rtcDoc::doc":
+        description: on_startup description
+        postCondition: on_startup Post_condition
+        preCondition: on_startup Pre_condition
+    onStateUpdate:
+      "rtcDoc::doc":
+        description: on_state_update description
+        postCondition: on_state_update Post_condition
+        preCondition: on_state_update Pre_condition
+  dataPorts: 
+    -
+      name: inport1
+      portType: DataInPort
+      type: "RTC::TimedLong"
+      interfaceType: CorbaPort
+      dataflowType: "Push,Pull"
+      subscriprionType: "Periodic,New,Flush"
+      idlFile: DataPort1.idl
+      "rtcDoc::doc":
+        type: In1Type
+        description: In1Description
+        number: In1Number
+        occerrence: In1Occerrence
+        operation: In1Operation
+        semantics: In1Semantics
+        unit: In1Unit
+      "rtcExt::position": LEFT
+      "rtcExt::varname": In1Var
+  servicePorts: 
+    -
+      name: SrvPort1
+      "rtcDoc::doc":
+        description: ServicePort1 description
+        ifdescription: ServicePort1 I/F description
+      "rtcExt::position": LEFT
+      serviceInterface: 
+        -
+          direction: Provided
+          "rtcDoc::doc":
+            description: if1 Description
+            docArgument: if1 Argument
+            docException: if1 Exception
+            docPostCondition: if1 PostCond
+            docPreCondition: if1 PreCond
+            docReturn: if1 Return
+          idlFile: IF1Idlfile.idl
+          instanceName: IF1Instance
+          name: S1IF1
+          path: IF1SearchPath
+          type: IF1Type
+          varname: IF1VarName
+  configurationSet: 
+    configuration: 
+      - 
+        name: config1
+        type: int
+        varname: var1
+        defaultValue: ""
+        "rtcDoc::doc":
+          constraint: config_constraint1
+          dataname: dataname1
+          defaultValue: default1
+          description: config_Desc1
+          range: config_range1
+          unit: config_unit1
+  parameters: 
+    -
+      defaultValue: param_def1
+      name: param1
+    -
+      defaultValue: param_def2
+      name: param2
+
+"""
+
+
 class Struct:
   def __init__(self):
     return
 
-conf_path = ['']
+plib = get_python_lib()
 
-if platform == "win32":
-  python_path = os.environ['PYTHONPATH'].split(";")
-  pyhelper_path = python_path[0] + "\\OpenRTM_aist\\utils\\rtc-template"
+if sys.platform == "win32":
+  pyhelper_path = os.path.join(plib,"OpenRTM_aist\\rtc-template")
 else:
-  conf_path = os.popen("which rtm-config", "r").read().split("\n")
-  if conf_path[0] != '':
-    libdir_path = os.popen("rtm-config --libdir", "r").read().split("\n")
-    pyhelper_path = libdir_path[0] + "/py_helper"
-  else:
-    python_path = os.environ['PYTHONPATH'].split(":")
-    pyhelper_path = python_path[0] + "/OpenRTM_aist/utils/rtc-template"
+  pyhelper_path = os.path.join(plib,"/OpenRTM_aist/utils/rtc-template")
+
 sys.path.append(pyhelper_path)
 
 # Option format
 opt_args_fmt = ["help",
-    "module-name=",
-    "module-type=",
-    "module-desc=",
-    "module-version=",
-    "module-vendor=",
-    "module-category=",
-    "module-comp-type=",
-    "module-act-type=",
-    "module-max-inst=",
-    "module-lang=",
+                "module-name=",
+                "module-type=",
+                "module-desc=",
+                "module-version=",
+                "module-vendor=",
+                "module-category=",
+                "module-comp-type=",
+                "module-act-type=",
+                "module-max-inst=",
+                "module-lang=",
                 "config=",
-    "inport=",
-    "outport=",
-    "service=",
-    "service-idl=",
-    "consumer=",
-    "consumer-idl=",
-    "idl-include=",
-    "backend="]
+                "inport=",
+                "outport=",
+                "service=",
+                "service-idl=",
+                "consumer=",
+                "consumer-idl=",
+                "idl-include=",
+                "backend="]
 
 
 def usage_short():
@@ -144,6 +269,7 @@
     [--idl-include=[path]]                Search path for IDL compile
 
 """
+
 def usage_long():
   """
   Help message
@@ -151,7 +277,7 @@
   print """
     --output[=output_file]:
         Specify base name of output file. If 'XXX' is specified,
-        C++ source codes XXX.cpp, XXX.h, XXXComp.cpp Makefile.XXX is generated.
+        Python source codes XXX.py is generated.
 
     --module-name[=name]:
         Your component's base name. This string is used as module's
@@ -174,7 +300,7 @@
 
     --module-comp-type[=component_type]:
         Specify component type.
-      'STATIC', 'UNIQUE', 'COMMUTATIVE' are acceptable.
+            'STATIC', 'UNIQUE', 'COMMUTATIVE' are acceptable.
 
     --module-act-type[=activity_type]:
         Specify component activity's type.
@@ -188,11 +314,6 @@
         configuration value identifier. This character string is also used as
         variable name in the source code. The 'Type' is type of configuration
         value. The type that can be converted to character string is allowed.
-        In C++ language, the type should have operators '<<' and '>>' that
-        are defined as
-        'istream& operator<<(Type)'
-        and
-        'ostream& operator>>(Type)'.
 
     --inport=[PortName:Type]:
         Specify InPort's name and type. 'PortName' is used as this InPort's
@@ -207,7 +328,7 @@
         'Type' is OutPort's variable type. The acceptable types are,
         Timed[ Short | Long | UShort | ULong | Float | Double | Char | Boolean
         | Octet | String ] and its sequence types.
-    
+                
     --service=[PortName:Name:Type]:
         Specify service name, type and port name.
         PortName: The name of Port to which the interface belongs.
@@ -221,7 +342,7 @@
         Specify IDL file of service interface.
         For simplicity, please define one interface in one IDL file, although
         this IDL file can include two or more interface definition,
-    
+                
     --consumer=[PortName:Name:Type]:
         Specify consumer name, type and port name.
         PortName: The name of Port to which the consumer belongs.
@@ -235,18 +356,18 @@
         Specify IDL file of service consumer.
         For simplicity, please define one interface in one IDL file, although
         this IDL file can include two or more interface definition,
-  
+        
 
 Example:
-    rtc-template -bcxx \\
+    rtc-template -bpython \\
     --module-name=Sample --module-desc='Sample component' \\
     --module-version=0.1 --module-vendor=AIST --module-category=Generic \\
     --module-comp-type=DataFlowComponent --module-act-type=SPORADIC \\
     --module-max-inst=10  \\
     --config=int_param0:int:0 --config=int_param1:int:1 \\
     --config=double_param0:double:3.14 --config=double_param1:double:9.99 \\
-    --config="str_param0:std::string:hoge" \\
-    --config="str_param1:std::string:foo" \\
+    --config="str_param0:string:hoge" \\
+    --config="str_param1:string:foo" \\
     --inport=Ref:TimedFloat --inport=Sens:TimedFloat \\
     --outport=Ctrl:TimedDouble --outport=Monitor:TimedShort \\
     --service=MySvcPort:myservice0:MyService \\
@@ -260,108 +381,142 @@
   usage_short()
   usage_long()
   return
+                
 
-class ModuleProfile:
+def CreateBasicInfo(opts):
   """
-  ModuleProfile class
+  MakeModuleProfile
 
-  This class create RTM module profile for ezt.
+  Create ModuleProfile list from command options
   """
-  
-  def __init__(self, name="", desc="", type="", version="", vendor="",
-         category="", comp_type="", act_type="",
-         max_inst="", lang=""):
+  mapping = {
+    'name': 'name',
+    'desc': 'description',
+    'version': 'version',
+    'vendor': 'vendor',
+    'category': 'category',
+    'comp-type': 'componentType',
+    'act-type': 'activityType',
+    'type': 'componentKind',
+    'max-inst': 'maxInstances'
+    }
 
-    self.name = name
-    self.desc = desc
-    self.type = type
-    self.version = version
-    self.vendor = vendor
-    self.category = category
-    self.comp_type = comp_type
-    self.act_type = act_type
-    self.max_inst = max_inst
-    self.lang = lang
-    return
-  
+  # default "basicInfo"
+  prof = {
+    "name": "",
+    "description": "",
+    "version": "1.0.0",
+    "vendor": "",
+    "category": "",
+    "componentType": "STATIC",
+    "activityType": "PERIODIC",
+    "componentKind": "DataFlowComponent",
+    "maxInstances": "1",
+    "abstract": "",
+    "executionRate": "1000.0",
+    "executionType": "PeriodicExecutionContext",
+    "creationDate":
+      {
+      "day": "",
+      "hour": "",
+      "minute": "",
+      "month": "",
+      "second": "",
+      "year": ""
+      },
+    "updateDate":
+      {
+      "year": "",
+      "month": "",
+      "day": "",
+      "hour": "",
+      "minute": "",
+      "second": "",
+      },
+    "rtcDoc::doc":
+      {
+      "algorithm": "",
+      "creator": "",
+      "description": "",
+      "inout": "",
+      "license": "",
+      "reference": ""
+      },
+    "rtcExt::versionUpLog": []
+    }
 
-  def setValue(self, member, value):
-    member = member.replace("-", "_")
-    if hasattr(self, member):
-      setattr(self, member, value)
-    else:
-      print "Invalid option: --module-" + member + " " + value
-    return
-  
-  def setName(self, name):
-    self.name = name
-    return
-  
-  def setDesc(self, desc):
-    self.desc = desc
-    return
-  
-  def setVersion(self, version):
-    self.version = version
-    return
-  
-  def setVendor(self, vendor):
-    self.vendor = vendor
-    return
-  
-  def setCategory(self, vategory):
-    self.category = category
-    return
-
-  def setCompType(self, comp_type):
-    self.comp_type = comp_type
-    return
-
-  def setActType(self, act):
-    self.act_type = act_type
-    return
-
-  def setMaxInst(self, max_inst):
-    self.max_inst = max_inst
-    return
-
-  def printProfile(self):
-    print "----- Module Profile -----"
-    print "Name           ", self.name
-    print "Description    ", self.desc
-    print "Version        ", self.version
-    print "Vendor         ", self.vendor
-    print "Category       ", self.category
-    print "Component Type ", self.comp_type
-    print "Activity Type  ", self.act_type
-    print "Max Instancese ", self.max_inst
-    print "Language       ", self.lang
-    return
-    
-    
-
-def MakeModuleProfile(opts):
-  """
-  MakeModuleProfile
-
-  Create ModuleProfile list from command options
-  """
-  prof = ModuleProfile()
+  # obtain --module-xxx options' values
   for opt, arg in opts:
     if opt.find("--module-") == 0:
       var = opt.replace("--module-","")
-      prof.setValue(var, arg)
+      if prof.has_key(mapping[var]):
+        prof[mapping[var]] = arg
+  # set creationDate
+  cDate = time.localtime()
+  i = 0
+  cDateKey = ['year', 'month', 'day', 'hour', 'minute', 'second']
+  for key in cDateKey:
+    prof["creationDate"][key] = cDate[i]
+    i += 1
+  # check empty values
+    empty = []
+    for key in prof.keys():
+      if prof[key] == "":
+        empty.append(key)
+
   return prof
 
+def CreateActions(opts):
+  actnames = [
+    "onInitialize",
+    "onFinalize",
+    "onActivated",
+    "onDeactivated",
+    "onAborting",
+    "onError",
+    "onReset",
+    "onExecute",
+    "onStateUpdate",
+    "onShutdown",
+    "onStartup",
+    "onRateChanged",
+    ]
 
-def MakeConfig(opts):
+  actions = {}
+  for a in actnames:
+    actions[a] = {
+      "rtcDoc::doc": {
+        "description": a + " description",
+        "postCondition": a + " Post_condition",
+        "preCondition": a + " Pre_condition"
+        },
+      "implemented": True
+      }
+  return actions
+
+def CreateConfigurationSet(opts):
   """
   MakeConfigurationParameters
-
+  
   Create Configuration list from command options
   """
   prof_list = []
-  cnt = 0
+  prof = {
+    "name": "",
+    "type": "",
+    "varname": "",
+    "defaultValue": "",
+    "rtcDoc::doc":
+      {
+      "type": "type", # type
+      "constraint": "constraint",
+      "dataname": "dataname",
+      "defaultValue": "default",
+      "description": "description",
+      "range": "range",
+      "unit": "unit"
+      }
+    }
   for opt, arg in opts:
     if opt == ("--config"):
       try:
@@ -372,133 +527,217 @@
         type    = re.sub("@@", "::", type)
         default = re.sub("@@", "::", default)
       except:
-        sys.stderr("Invalid option: " \
-             + opt \
-             + "=" \
-             + arg)
-      prof = Struct()
-      prof.name = name
-      prof.l_name = name.lower()
-      prof.u_name = name.upper()
-      prof.type = type
-      prof.default  = default
-      prof_list.append(prof)
-      cnt += 1
-  return prof_list
+        sys.stderr.write("Invalid option: " \
+                           + opt \
+                           + "=" \
+                           + arg)
+      tmp = copy.deepcopy(prof)
+      tmp["name"] = name
+      tmp["varname"] = name
+      tmp["l_name"] = name.lower()
+      tmp["u_name"] = name.upper()
+      tmp["type"] = type
+      tmp["defaultValue"] = default
+      tmp["rtcDoc::doc"]["defaultValue"] = default
+      prof_list.append(tmp)
+  return {'configuration': prof_list}
 
 
-def MakeDataPort(opts, port_type):
+def CreateDataPorts(opts):
   """
   MakePortProfile
 
   Create PortProfile list from command options
   """
   prof_list = []
+  prof = {
+    "name": "",
+    "portType": "",
+    "type": "",
+    "interfaceType": "CorbaPort",
+    "dataflowType": "Push,Pull",
+    "subscriptionType": "Periodic,New,Flush",
+    "idlFile": "",
+    "rtcDoc::doc":
+      {
+      "type": "",
+      "description": "",
+      "number": "",
+      "occerrence": "",
+      "operation": "",
+      "semantics": "",
+      "unit": ""
+      },
+    "rtcExt::position": "",
+    "rtcExt::varname": ""
+    }
   cnt = 0
+  portType = {"--inport": "DataInPort", "--outport": "DataOutPort"}
+  position = {"--inport": "LEFT", "--outport": "RIGHT"}
   for opt, arg in opts:
-    if opt == ("--" + port_type):
+    if opt == "--inport" or opt == "--outport":
       try:
+        arg = re.sub("::", "@@", arg)
         name, type = arg.split(":")
+        name    = re.sub("@@", "::", name)
+        type    = re.sub("@@", "::", type)
       except:
-        sys.stderr("Invalid option: " \
-             + opt \
-             + "=" \
-             + arg)
-      prof = Struct()
-      prof.name = name
-      prof.type = type
-      prof.num  = cnt
-      prof_list.append(prof)
+        sys.stderr.write("Invalid option: " \
+                           + opt \
+                           + "=" \
+                           + arg)
+      tmp = copy.deepcopy(prof)
+      tmp["name"] = name
+      tmp["portType"] = portType[opt]
+      tmp["type"] = type
+      tmp["num"]  = cnt
+      tmp["rtcDoc::doc"]["type"] = type
+      tmp["rtcDoc::doc"]["number"] = cnt
+      tmp["rtcExt::varname"] = name
+      tmp["rtcExt::position"] = position[opt]
+      prof_list.append(tmp)
       cnt += 1
+
   return prof_list
 
 
-def MakePortInterface(opts, port_type):
+def CreateServicePorts(opts):
   """
   MakePortInterface
-
+  
   Create Port interface profile list from command options
   """
   prof_list = []
-  cnt = 0
-  for opt, arg in opts:
-    if opt == "--" + port_type:
-      try:
-        port, name, type = arg.split(":")
-      except:
-        sys.stderr.write("Invalid option: " \
-             + opt \
-             + "=" \
-             + arg)
-      prof = Struct()
-      prof.port = port
-      prof.name = name
-      prof.type = type
-      prof.num  = cnt
-      prof_list.append(prof)
-      cnt += 1
-  return prof_list
 
-def MakeCorbaPort(opts):
-  """
-  MakeCorbaPort
+  prof = {
+    "name": "",
+    "rtcDoc::doc":
+      {
+      "description": "",
+      "ifdescription": "",
+      },
+    "rtcExt::position": "LEFT",
+    "serviceInterface": []
+    }
+  ifprof = {
+    "name": "",
+    "type": "",
+    "direction": "",
+    "varname": "",
+    "instanceName": "",
+    "idlFile": "",
+    "path": "",
+    "rtcDoc::doc":
+      {
+      "description": "",
+      "docArgument": "",
+      "docException": "",
+      "docPostCondition": "",
+      "docPreCondition": "",
+      "docReturn": ""
+      }
+    }
 
-  Create Corba Port profile list from command options
-  """
-  prof_list = []
+  def findport(prof_list, port_name):
+    for p in prof_list:
+      if p["name"] == port_name:
+        return p
+    return None
+  def lr(port):
+    cnt = {"Provided": 0, "Required": 0}
+    for ifprof in port["serviceInterface"]:
+      cnt[ifprof["direction"]] += 1
+    if cnt["Provided"] < cnt["Required"]:
+      return "LEFT"
+    else:
+      return "RIGHT"
+
   cnt = 0
+  ifType = {"--service": "Provided", "--consumer": "Required"}
   for opt, arg in opts:
-    if opt == ("--" + "service") or opt == ("--" + "consumer"):
+    if opt == "--service" or opt == "--consumer":
       try:
-        port, name, type = arg.split(":")
+        arg = re.sub("::", "@@", arg)
+        portname, name, type = arg.split(":")
+        portname = re.sub("@@", "::", portname)
+        name     = re.sub("@@", "::", name)
+        type     = re.sub("@@", "::", type)
       except:
         sys.stderr.write("Invalid option: " \
-             + opt \
-             + "=" \
-             + arg)
-      dup = False
-      for p in prof_list:
-        if p.name == port:
-          dup = True
-      if dup == False:
-        prof = Struct()
-        prof.name = port
-        prof.num  = cnt
-        prof_list.append(prof)
-        cnt += 1
+                           + opt \
+                           + "=" \
+                           + arg)
+      port = findport(prof_list, portname)
+      if port == None:
+        port = copy.deepcopy(prof)
+        port["name"] = portname
+        prof_list.append(port)
+          
+      tmp = copy.deepcopy(ifprof)
+      tmp["name"] = name
+      tmp["type"] = type
+      tmp["direction"] = ifType[opt]
+      tmp["varname"] = name
+      tmp["instanceName"] = name
+      idlfname = FindIdlFile(opts, type)
+      if idlfname == None:
+        print "Error:"
+        print "IDL file not found for a interface: ", type
+        sys.exit(1)
+      tmp["idlFile"] = idlfname
+      port["serviceInterface"].append(tmp)
+      port["rtcExt::position"] = lr(port)
+      cnt += 1
   return prof_list
 
 
-
-def MakeServiceIDL(opts):
-  """
-  MakeServiceIDL
-
-  Create ServiceIDL list from command options
-  """
-  idl_list = []
-
+def FindIdlFile(opts, ifname):
+  _re_text = "interface\s+" + ifname
   for opt, arg in opts:
-    if opt.find("--service-idl") == 0:
-      svc_idl = Struct()
-      svc_idl.idl_fname = arg
-      svc_idl.idl_basename, dummy = arg.split(".")
-      idl_list.append(svc_idl)
-  return idl_list
+    if opt == "--service-idl" or opt == "--consumer-idl":
+      fname = arg
+      fd = open(fname, "r")
+      if fd == None:
+        print "IDL file not found: ", arg
+        sys.exit(1)
+      t = fd.read()
+      if None != re.compile(_re_text).search(t):
+        fd.close()
+        return fname
+      fd.close()
+  return None
 
+def PickupIDLFiles(dict):
+  svcidls = {}
+  cnsidls = {}
+  for svc in dict["servicePorts"]:
+    for sif in svc["serviceInterface"]:
+      if sif["direction"] == "Provided":
+        svcidls[sif["idlFile"]] = ""
+      elif sif["direction"] == "Required":
+        if not svcidls.has_key(sif["idlFile"]):
+          cnsidls[sif["idlFile"]] = ""
+  dict["service_idl"] = []
+  dict["consumer_idl"] = []
+  for f in svcidls.keys():
+    idl = {}
+    idl["idl_fname"] = f
+    idl["idl_basename"] = f.split(".")[0]
+    dict["service_idl"].append(idl)
+  for f in cnsidls.keys():
+    idl = {}
+    idl["idl_fname"] = f
+    idl["idl_basename"] = f.split(".")[0]
+    dict["consumer_idl"].append(idl)
+  return
 
-def MakeConsumerIDL(opts):
-  idl_list = []
-  for opt, arg in opts:
-    if opt == "--consumer-idl":
-      svc_idl = Struct()
-      svc_idl.idl_fname = arg
-      svc_idl.idl_basename, dummy = arg.split(".")
-      idl_list.append(svc_idl)
-  return idl_list
+def CreateId(dict):
+  dict["id"] = "RTC:" + \
+      dict["basicInfo"]["vendor"] + "." + \
+      dict["basicInfo"]["category"] + "." + \
+      dict["basicInfo"]["name"] + ":" + \
+      dict["basicInfo"]["version"]
 
-
-
 def find_opt(opts, value, default):
   for opt, arg in opts:
     if opt.find(value) == 0:
@@ -506,7 +745,6 @@
 
   return default
 
-
 def find_opt_list(opts, value, default):
   list = []
   if len(default) > 0:
@@ -530,8 +768,7 @@
     self.opts = []
     self.available()
     return
-    
-
+                
   def available(self):
     path_list = [pyhelper_path, "."]
     for path in path_list:
@@ -545,12 +782,10 @@
             be = Backend(mod_name, mod)
             self.backends[opt_name] = be
           except:
-            print "Invalid backend: ", f
             pass
 
     return self.backends
 
-
   def check_args(self, args):
     for opt in args:
       if opt.find('-b') == 0:
@@ -569,7 +804,6 @@
           sys.exit(-1)
     return self.opts
 
-
   def get_opt_fmts(self):
     fmts = []
     for be in self.opts:
@@ -581,18 +815,17 @@
     print "The following backends are available."
     space = 10
     for key in self.backends:
-      desc = self.backends[key].mod.description()     
+      desc = self.backends[key].mod.description()                     
       print "    -b" + key + ("." * (space - len(key))) + desc
     print """
 Backend [xxx] specific help can be available by the following options.
     -bxxx --help|-h or --backend=xxx --help|-h
-  """
+        """
     return
 
-
   def usage(self):
     for be in self.opts:
-      print self.backends[be].mod.usage()     
+      print self.backends[be].mod.usage()                     
       print ""
     return
 
@@ -602,12 +835,11 @@
       print ""
     return
 
-
   def generate_code(self, data, opts):
     for be in self.opts:
       self.backends[be].obj(data, opts).print_all()
     return
-    
+                
 
 def fmtd_args(width, args):
   arg_fmt = [""]
@@ -626,7 +858,6 @@
 
 def main():
   global opt_args_fmt
-  global conf_path
 
   backends = BackendLoader()
   backends.check_args(sys.argv[1:])
@@ -647,8 +878,6 @@
 
   output = None
   verbose = False
-  output_cxx = False
-  output_python = False
 
   for o, a in opts:
     if o == "-v":
@@ -667,42 +896,36 @@
       output = a
       # ...
 
-  prefix = [' ']
-  if conf_path[0] != '':
-    prefix = os.popen("rtm-config --prefix", "r").read().split("\n")
+  idl_dir = os.path.join(get_python_lib(),"OpenRTM_aist\\RTM_IDL")
   idl_inc = []
-  if prefix[0] != '':
-    idl_inc.append(prefix[0] + "/include/rtm/idl")
-    idl_inc.append(prefix[0] + "/include/rtm")
+  idl_inc.append(idl_dir)
   idl_inc.append(".")
 
   # Create dictionary for ezt
-  data = {
-    'module':       MakeModuleProfile(opts),
-                'config':       MakeConfig(opts),
-    'inport':       MakeDataPort(opts, "inport"),
-    'outport':      MakeDataPort(opts, "outport"),
-    'service':      MakePortInterface(opts, "service"),
-    'consumer':     MakePortInterface(opts, "consumer"),
-                'corbaport':    MakeCorbaPort(opts),
-    'service_idl':  MakeServiceIDL(opts),
-    'consumer_idl': MakeConsumerIDL(opts),
-    'idl_include':  find_opt_list(opts, "--idl-include", idl_inc),
-    'fname':        output,
-    'args':         sys.argv,
-    'fmtd_args':    fmtd_args(70, sys.argv)
-    }
+  data = {'basicInfo':        CreateBasicInfo(opts),
+          'actions':          CreateActions(opts),
+          'configurationSet': CreateConfigurationSet(opts),
+          'dataPorts':        CreateDataPorts(opts),
+          'servicePorts':     CreateServicePorts(opts),
+          'args':             sys.argv,
+          'fmtd_args':        fmtd_args(70, sys.argv),
+          'idl_include':      idl_inc
+          }
+  CreateId(data)
+  PickupIDLFiles(data)
 
-  if data['fname'] == None:
-    data['fname'] = data['module'].name
-
+  if not data.has_key('fname'):
+    data['fname'] = data['basicInfo']['name']
   backends.generate_code(data, opts)
 
-  import README_src
-  readme_src = README_src.README_src(data)
-  readme_src.print_all()
+  import README_gen
+  readme = README_gen.README_gen(data)
+  readme.print_all()
+  import profile_gen
+  profile = profile_gen.profile_gen(data)
+  profile.print_all()
   return
-    
+        
 
 if __name__ == "__main__":
   main()

Modified: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/uuid.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/uuid.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/uuid.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -46,7 +46,7 @@
 This module works with Python 2.3 or higher."""
 
 __author__ = 'Ka-Ping Yee <ping at zesty.ca>'
-__date__ = '$Date: 2007/07/20 16:16:21 $'.split()[1].replace('/', '-')
+__date__ = '$Date: 2007-07-20 16:16:21 $'.split()[1].replace('/', '-')
 __version__ = '$Revision: 1.1.2.1 $'.split()[1]
 
 RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [

Deleted: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/vcproject_gen.py
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/vcproject_gen.py	2011-10-19 09:36:55 UTC (rev 495)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/vcproject_gen.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -1,362 +0,0 @@
-#!/usr/bin/env python
-# -*- Python -*-
-#
-
-#  @file vcproject_gen.py
-#  @brief rtc-template VC++ project file generator class
-#  @date $Date: 2007/09/26 07:43:29 $
-#  @author Noriaki Ando <n-ando at aist.go.jp> and S.Kurihara
-
-import re
-import os
-import time
-import StringIO
-import ezt
-import gen_base
-import uuid
-
-def description():
-	return "VC++ project-file generator"
-
-def usage_short():
-	"""
-	VC++ project-file generator specific usage (short version)
-	"""
-	return """
-Options for VC++ backend:
-
-"""
-
-def usage():
-	"""
-	VC++ project-file generator specific usage
-	"""
-	return """
--------------------------------
-  Help for VC++ project-file geenrator
--------------------------------
-"""
-
-def get_opt_fmt():
-	opt_args_fmt = []
-	return opt_args_fmt
-
-
-proj_file = """<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioProject
-	ProjectType="Visual C++"
-	Version="[vc_version]"
-	Name="[fname]"
-	ProjectGUID="[guid]"
-	RootNamespace="[fname]"
-	Keyword="Win32Proj"
-	>
-	<Platforms>
-		<Platform
-			Name="Win32"
-		/>
-	</Platforms>
-	<ToolFiles>
-	</ToolFiles>
-	<Configurations>
-		<Configuration
-			Name="Debug|Win32"
-			OutputDirectory=".\\Debug"
-			IntermediateDirectory=".\\Debug"
-			ConfigurationType="1"
-			InheritedPropertySheets=".\\OpenRTM-aist.vsprops"
-			CharacterSet="2"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				Optimization="0"
-				PreprocessorDefinitions="USE_stub_in_nt_dll;WIN32;_DEBUG;_CONSOLE;__WIN32__;__x86__;_WIN32_WINNT=0x0400;__NT__;__OSVERSION__=4;_CRT_SECURE_NO_DEPRECATE"
-				MinimalRebuild="true"
-				BasicRuntimeChecks="3"
-				RuntimeLibrary="3"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="false"
-				DebugInformationFormat="4"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="ACEd.lib RTC041d.lib omniORB407_rtd.lib omniDynamic407_rtd.lib omnithread32_rtd.lib advapi32.lib ws2_32.lib mswsock.lib"
-				OutputFile="$(OutDir)\\[fname].exe"
-				LinkIncremental="2"
-				IgnoreDefaultLibraryNames=""
-				GenerateDebugInformation="true"
-				SubSystem="1"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-		<Configuration
-			Name="Release|Win32"
-			OutputDirectory=".\\Release"
-			IntermediateDirectory=".\\Release"
-			ConfigurationType="1"
-			InheritedPropertySheets=".\\OpenRTM-aist.vsprops"
-			CharacterSet="0"
-			WholeProgramOptimization="0"
-			>
-			<Tool
-				Name="VCPreBuildEventTool"
-			/>
-			<Tool
-				Name="VCCustomBuildTool"
-			/>
-			<Tool
-				Name="VCXMLDataGeneratorTool"
-			/>
-			<Tool
-				Name="VCWebServiceProxyGeneratorTool"
-			/>
-			<Tool
-				Name="VCMIDLTool"
-			/>
-			<Tool
-				Name="VCCLCompilerTool"
-				PreprocessorDefinitions="USE_stub_in_nt_dll;WIN32;NDEBUG;_CONSOLE;__WIN32__;__x86__;_WIN32_WINNT=0x0400;__NT__;__OSVERSION__=4"
-				RuntimeLibrary="2"
-				UsePrecompiledHeader="0"
-				WarningLevel="3"
-				Detect64BitPortabilityProblems="false"
-				DebugInformationFormat="3"
-			/>
-			<Tool
-				Name="VCManagedResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCResourceCompilerTool"
-			/>
-			<Tool
-				Name="VCPreLinkEventTool"
-			/>
-			<Tool
-				Name="VCLinkerTool"
-				AdditionalDependencies="ACE.lib RTC041.lib omniORB407_rt.lib omniDynamic407_rt.lib omnithread32_rt.lib advapi32.lib ws2_32.lib mswsock.lib"
-				OutputFile="$(OutDir)/$(ProjectName).exe"
-				LinkIncremental="1"
-				GenerateDebugInformation="false"
-				SubSystem="1"
-				OptimizeReferences="2"
-				EnableCOMDATFolding="2"
-				LinkTimeCodeGeneration="0"
-				TargetMachine="1"
-			/>
-			<Tool
-				Name="VCALinkTool"
-			/>
-			<Tool
-				Name="VCManifestTool"
-			/>
-			<Tool
-				Name="VCXDCMakeTool"
-			/>
-			<Tool
-				Name="VCBscMakeTool"
-			/>
-			<Tool
-				Name="VCFxCopTool"
-			/>
-			<Tool
-				Name="VCAppVerifierTool"
-			/>
-			<Tool
-				Name="VCWebDeploymentTool"
-			/>
-			<Tool
-				Name="VCPostBuildEventTool"
-			/>
-		</Configuration>
-	</Configurations>
-	<References>
-	</References>
-	<Files>
-		<Filter
-			Name="source file"
-			Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"
-			UniqueIdentifier="[SourceGUID]"
-			>
-			<File
-				RelativePath=".\\[fname_cpp]"
-				>
-			</File>
-			<File
-				RelativePath=".\\[fname_comp]"
-				>
-			</File>
-		</Filter>
-		<Filter
-			Name="header file"
-			Filter="h;hpp;hxx;hm;inl;inc;xsd"
-			UniqueIdentifier="[HeaderGUID]"
-			>
-			<File
-				RelativePath=".\\[fname_h]"
-				>
-			</File>
-		</Filter>
-		<Filter
-			Name="resource file"
-			Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav"
-			UniqueIdentifier="[ResourceGUID]"
-			>
-		</Filter>
-	</Files>
-	<Globals>
-	</Globals>
-</VisualStudioProject>
-""" 
-
-props_file = """<?xml version="1.0" encoding="shift_jis"?>
-<VisualStudioPropertySheet
-	ProjectType="Visual C++"
-	Version="8.00"
-	Name="OpenRTM-aist-0.4"
-	>
-	<Tool
-		Name="VCCLCompilerTool"
-		AdditionalIncludeDirectories=""$(rtm_root)";"$(rtm_root)\\rtm\\idl";"$(ace_include)";"$(omni_include)";."
-	/>
-	<Tool
-		Name="VCLinkerTool"
-		AdditionalLibraryDirectories=""$(rtm_root)\\bin";"$(ace_libdir)";"$(omni_libdir)""
-	/>
-	<UserMacro
-		Name="ace_root"
-		Value="%ACE_ROOT%"
-	/>
-	<UserMacro
-		Name="omni_root"
-		Value="%OMNI_ROOT%"
-	/>
-	<UserMacro
-		Name="rtm_root"
-		Value="%RTM_ROOT%"
-	/>
-	<UserMacro
-		Name="ace_include"
-		Value="$(ace_root)"
-	/>
-	<UserMacro
-		Name="ace_libdir"
-		Value="$(ace_root)\\lib"
-	/>
-	<UserMacro
-		Name="omni_include"
-		Value="$(omni_root)\\include"
-	/>
-	<UserMacro
-		Name="omni_libdir"
-		Value="$(omni_root)\\lib\\x86_win32"
-	/>
-	<UserMacro
-		Name="omni_bin"
-		Value="$(omni_root)\\bin\\x86_win32"
-	/>
-	<UserMacro
-		Name="rtm_includes"
-		Value=""$(rtm_root)";"$(rtm_root)\\rtm\\idl";"$(ace_include)";"$(omni_include)";."
-	/>
-	<UserMacro
-		Name="rtm_libdir"
-		Value=""$(rtm_root)\\bin";"$(ace_libdir)";"$(omni_libdir)";."
-	/>
-	<UserMacro
-		Name="rtm_path"
-		Value=""$(rtm_root)\\bin";"$(rtm_root)\\build";"$(omni_bin)""
-	/>
-</VisualStudioPropertySheet>
-"""
-
-
-class vcproject_gen(gen_base.gen_base):
-	"""
-	VC++ project-file generator
-	"""
-	_fname_space = 16
-	def __init__(self, data, opts):
-		self.data = data.copy()
-
-		self.data["begin_brace"] = "["
-		self.data["end_brace"] = "]"
-		self.data["vcproject_file"] = self.data["fname"] + ".vcproj"
-		self.data["props_file"] = "OpenRTM-aist.vsprops"
-		self.data["l_name"] = self.data["fname"].lower()
-		self.data["guid"] = uuid.uuid1()
-		self.data["SourceGUID"] = uuid.uuid1()
-		self.data["HeaderGUID"] = uuid.uuid1()
-		self.data["ResourceGUID"] = uuid.uuid1()
-		self.data["vc_version"] = "8.00"
-		self.data["fname_h"] = self.data["fname"] + ".h"
-		self.data["fname_cpp"] = self.data["fname"] + ".cpp"
-		self.data["fname_comp"] = self.data["fname"] + "Comp.cpp"
-
-		self.tags = {}
-		self.gen_tags(self.tags)
-
-		return
-
-	def print_vcproject(self):
-		"""
-		Generate VC++ project-file
-		"""
-		self.gen(self.data["props_file"],
-			 props_file, self.data, self.tags)
-
-		self.gen(self.data["vcproject_file"],
-			 proj_file, self.data, self.tags)
-		return
-
-
-	def print_all(self):
-		self.print_vcproject()

Copied: trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/yat.py (from rev 495, branches/RELENG_1_1/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/yat.py)
===================================================================
--- trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/yat.py	                        (rev 0)
+++ trunk/OpenRTM-aist-Python/OpenRTM_aist/utils/rtc-template/yat.py	2011-10-19 09:41:38 UTC (rev 496)
@@ -0,0 +1,835 @@
+#!/usr/bin/env python
+#
+# @brief YAT: YAml Template text processor
+# @date $Date: 2008-02-09 20:04:27 $
+# @author Norkai Ando <n-ando at aist.go.jp>
+#
+# Copyright (C) 2008 Noriaki Ando, All rights reserved.
+#
+# $Id: yat.py 775 2008-07-28 16:14:45Z n-ando $
+#
+
+#
+# Usage:
+#------------------------------------------------------------
+# import yaml
+# import yat
+#
+# dict   = yaml.load(open(filename, "r").read())
+# t      = yat.Template(template, "\[", "\]")
+# result = t.generate(dict)
+#------------------------------------------------------------
+#
+# 1. Simple directive:
+#    [dictionary_key]
+#
+#    Nested dictionaries can be expressed by dotted expression.
+#
+# example:
+# dict = {"a": "This is a",
+#         "b": {"1": "This is b.1",
+#               "2": "This is b.2"}
+#        }
+#
+# template:
+# [a]
+#
+# [b.1]
+#
+# [b.2]
+#
+# result:
+# This is a
+# This is b.1
+# This is b.2
+#
+#
+# 2. "for" directive:
+#    [for key in list] statement [endfor]
+#
+#    Iterative evaluation for listed values is performed by "for" statement.
+#    In iteration at each evaluation, the value of the list is assigned to
+#    "key". The "key" also can be the nested dictionary directive.
+#
+# example:
+# dict = {"list": [0, 1, 2],
+#         "listed_dict": [
+#           {"name": "x", "value": "1.0"},
+#           {"name": "y", "value": "0.2"},
+#           {"name": "z", "value": "0.1"}]}
+#
+# template:
+# [for lst in list]
+# [lst],  
+# [endfor]
+# [for lst in listed_dict]
+# [lst.name]: [lst.value]
+# 
+# [endfor]
+#
+# result:
+# 1, 2, 3,
+# x: 1.0
+# y: 0.2
+# x: 0.1
+#
+#
+# 3. "if-index" directive:
+#    [for key in val]
+#    [if-index key is first|even|odd|last|NUMBER] statement1
+#    [elif-index key is first|even|odd|last|NUMBER] statement2
+#    [endif][endfor]
+#
+#    "if-index" is used to specify the index of the "for" iteration.
+#    The "key" string which is defined in the "for" statement is used as index.
+#    A number or predefined directives such as "first", "even", "odd" and
+#    "last" can be used to specify the index.
+#
+# example:
+# dict = {"list": [0,1,2,3,4,5,6,7,8,9,10]}
+#
+# template:
+# [for key in list]
+# [if-index key is 3] [key] is hoge!!
+# [elif-index key is 6] [key] is foo!!
+# [elif-index key is 9] [key] is bar!!
+# [elif-index key is first] [key] is first
+# [elif-index key is last] Omoro-------!!!!
+# [elif-index key is odd] [key] is odd number
+# [elif-index key is even] [key] is even number
+# [endif]
+# [endfor]
+#
+# result:
+#  0 is first
+#  1 is odd number
+#  2 is even number
+#  3 is hoge!!
+#  4 is even number
+#  5 is odd number
+#  6 is foo!!
+#  7 is odd number
+#  8 is even number
+#  9 is bar!!
+#  Omoro-------!!!!
+#
+#
+# 4. "if" directive: [if key is value] text1 [else] text2 [endif]
+#    If "key" is "value", "text1" appears, otherwise "text2" appears.
+#
+# example:
+# dict = {"key1": "a", "key2": "b"}
+#
+# template:
+# [if key1 is a]
+# The key1 is "a".
+# [else]
+# This key1 is not "a".
+# [endif]
+#
+# result:
+# The key1 is "a".
+#
+#
+# 5. "if-any" directive: [if-any key1] text1 [else] text2 [endif]
+#    If the "key1" exists in the dictionary, "text1" appears, otherwise
+#    "text2" appears.
+#
+# example:
+# dict = {"key1": "a", "key2": "b"}
+#
+# template:
+# [if-any key1]
+# key1 exists.
+# [endif][if-any key3]
+# key3 exists.
+# [else]
+# key3 does not exists.
+# [endif]
+#
+# result:
+# key1 exists.
+# key3 does not exists.
+#
+#
+# 6. bracket and comment:
+#    [[] is left bracket if begin mark is "["
+#    [# comment ] is comment if begin/end marks are "[" and "]"
+#
+# example:
+# dict = {}
+#
+# template:
+# [[]bracket]
+# [# comment]
+#
+# result:
+# [bracket]
+#
+import string
+import re
+from types import StringType, IntType, FloatType, DictType, ListType, ClassType
+import sys
+
+class Template:
+    """
+    usage:
+      tempalte_text = read template text from file
+      dictionary    = create dictionaly by using yaml
+      t = Template(tempalte_text)
+      generated_text = t.generate(dictionary)
+
+    """
+    
+    def __init__(self, template, begin_mark="\[", end_mark="\]"):
+        self.__procs = [self.__proc_text,
+                        self.__proc_cmd,
+                        self.__proc_bracket]
+        self.template = template
+
+        # regular expression to devide text into DIRECTIVE, BRACKET and COMMENT
+        #
+        # default:
+        # START_MARK: "["
+        # END_MARK  : "]"
+        # -> START_MARK and END_MARK can be given in ctor
+        #
+        # ITEM: (?:"(?:[^\\"]|\\.)*"|[-\w.]+)
+        # \[(ITEM(?: +ITEM)*)\]|(\[\[\])|\[#[^\]]*\]
+        # ~~~~~~~~(1)~~~~~~ ~~(2)~~~ ~~~(3)~~~~~
+        # (1) COMMAND  : '[' ITEM (whitespace ITEM)* ']
+        #     ITEM     : STRING | NAME
+        #     STRING   : '"' (not-slash-or-dquote | '\' anychar)* '"'
+        #     NAME     : (alphanum | '_' | '-' | '.')+
+        # (2) BEGIN_MARK_ESCAPE : '[[]'
+        # (3) COMMENT  : '[#' not-rbracket
+        #        
+        # re_item      = r'(?:"(?:[^\\"]|\\.)*"|[-\w.]+)'
+        # re_command   = r'\[(%s(?: +%s)*)\]' % (re_item, re_item)
+        # re_beginmark = r'\[\[\]'
+        # re_comment   = r'\[#[^\]]*\]'
+        # re_parse     = re.compile(r'%s|(%s)|%s' 
+        #                     % (re_command, re_beginmark, re_comment))
+        # re_args      = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.]+')
+        #
+        #
+        re_item      = r'(?:"(?:[^\\"]|\\.)*"|[-\w.:]+)'
+        re_command   = r'%s(%s(?: +%s)*)%s' % \
+            (begin_mark, re_item, re_item, end_mark)
+        re_bracket   = r'%s%s%s' % \
+            (begin_mark, begin_mark, end_mark)
+        re_comment   = r'%s#[^%s]*%s' % \
+            (begin_mark, end_mark, end_mark)
+        self.begin_mark = begin_mark.replace("\\","")
+        self.re_parse = re.compile(r'%s|(%s)|%s' % \
+                                       (re_command, re_bracket, re_comment))
+        self.re_args  = re.compile(r'"(?:[^\\"]|\\.)*"|[-\w.:]+')
+        self.re_number = re.compile(r'[0-9]+')
+
+        # tokenize input text
+        self.token = self.re_parse.split(self.template)
+        self.token_len  = len(self.token)
+        
+        # initialize variables
+        self.script = program
+        self.indent = 4
+        self.script_level  = 2
+        self.level = 0
+        self.index = 0
+        self.cmd_cxt = []
+
+        # parse token
+        self.__parse_template(self.token)
+
+        return
+
+    def generate(self, dict):
+        # eval generated script
+        exec(self.script)
+        # script includes Generator class
+        gen = Generator(self.token, dict)
+        # execute generated script
+        return gen.generate()
+
+    def get_script(self):
+        return self.script
+
+    def __push_level(self):
+        self.level += 1
+
+    def __pop_level(self):
+        self.level -= 1
+
+    def __write_cmd(self, cmd):
+        tmp_cmd  = self.__indent()
+        tmp_cmd += "self.set_index(%s)\n" % (self.index)
+        self.script += tmp_cmd
+        self.__write_cmd_noindex(cmd)
+
+    def __write_cmd_noindex(self, cmd):
+        tmp_cmd  = self.__indent()
+        tmp_cmd += cmd + "\n"
+        self.script += tmp_cmd
+
+    def __parse_template(self, dict):
+        try:
+            # split into (TEXT DIRECTIVE BRACKET)* TEXT
+            self.__parse()
+        except YATException, e:
+            self.__print_error(e)
+            sys.exit(-1)
+
+    def __indent(self):
+        indent = " " * ((self.script_level + self.level) * self.indent)
+        return indent
+
+    def __parse(self):
+        while self.index < self.token_len:
+            self.__procs[self.index % 3]()
+            self.index += 1
+
+    def __proc_text(self):
+        if self.token[self.index] == None:
+            return
+        cmd_text = "self.write_token(%s)" % (self.index)
+        self.__write_cmd(cmd_text)
+        return True
+ 
+    def __proc_bracket(self):
+        if self.token[self.index] == None:
+            return
+        cmd_text = "self.write(\"" + self.begin_mark + "\")"
+        self.__write_cmd(cmd_text)
+        return True
+            
+    def __proc_cmd(self):
+        cmd = self.token[self.index]
+        try:
+            args = self.re_args.findall(cmd)
+        except:
+            return
+        self.del_nl_after_cmd()
+        argc = len(args)
+        if argc == 0:
+            raise InvalidDirective(self.lineno(), "_an empty directive_ ")
+
+        # simple directive
+        if argc == 1:
+            if   args[0] == "endfor":
+                self.__endfor_cmd(args)
+                return
+            elif args[0] == "else":
+                self.__else_cmd(args)
+                return
+            elif args[0] == "last":
+                self.__last_cmd(args)
+                return
+            elif args[0] == "endif":
+                self.__endif_cmd(args)
+                return
+            else:
+                self.__cmd(args)
+                return
+        elif argc == 2:
+            if args[0] == "if-any":
+                self.__if_any_cmd(args)
+                return
+        elif argc == 4: # [for key in value]
+            if args[0] == "for" and args[2] == "in":
+                self.__for_cmd(args)
+                return True
+            elif args[0] == "if" and args[2] == "is":
+                self.__if_cmd(args)
+            elif args[0] == "elif" and args[2] == "is":
+                self.__elif_cmd(args)
+            elif args[0] == "if-index" and args[2] == "is":
+                self.__if_index_cmd(args)
+            elif args[0] == "elif-index" and args[2] == "is":
+                self.__elif_index_cmd(args)
+            else:
+                raise InvalidDirective(self.lineno(), cmd)
+        else:
+            raise InvalidDirective(self.lineno(), cmd)
+        return True
+
+    def __cmd(self, args):
+        cmd_text = "self.write_dict(\"%s\")" % (args[0])
+        self.__write_cmd(cmd_text)
+
+    #------------------------------------------------------------
+    # [for] commands
+    # - for
+    # - last
+    # - endfor
+    #------------------------------------------------------------
+    def __for_cmd(self, args):
+        """
+        The following [for] directive
+          [for tmp_key in directive]
+        is converted into the following python command.
+          for i in len(directive):
+              self.dicts.append({tmp_key: ditective[i])
+        and, endfor directive terminate as the following,
+              self.dicts.pop()
+        """
+        key = args[1]
+        directive = args[3]
+        # (key)     : variable string of index variable for [for] block
+        # (key)_list: list value of specified directive
+        # (key)_len : length of the list
+        cmd_text = "%s_list = self.get_list(\"%s\")" % (key, directive)
+        self.__write_cmd(cmd_text)
+        cmd_text = "%s_len = len(%s_list)" % (key, key)
+        self.__write_cmd(cmd_text)
+        cmd_text = "for %s_index in range(len(%s_list)):" % (key, key)
+        self.__write_cmd(cmd_text)
+        self.__push_level()
+        cmd_text = "self.push_dict({\"%s\": %s_list[%s_index]})" \
+            % (key, key, key)
+        self.__write_cmd(cmd_text)
+        self.cmd_cxt.append("for")
+
+    def __endfor_cmd(self, args):
+        try:
+            cxt = self.cmd_cxt.pop()
+            if cxt != "for":
+                raise UnmatchedBlock(self.lineno(), "endfor")
+            self.__write_cmd("self.pop_dict()")
+            self.__pop_level()
+        except:
+            print args, self.lineno()
+            raise UnmatchedBlock(self.lineno(), "endfor")
+        return
+
+    # end of [for] commands
+    #------------------------------------------------------------
+
+    #------------------------------------------------------------
+    # [if] commands
+    # - if
+    # - if-index
+    # - if-any
+    #------------------------------------------------------------
+    def __if_cmd(self, args):
+        """
+        The following [if] directive
+          [if directive is string]
+        is converted into the following python command.
+          if self.__get_string() == "string":
+        """
+        directive = args[1]
+        string = args[3]
+        cmd_text = "if self.get_text(\"%s\") == \"%s\":" % \
+            (directive, string)
+        self.__write_cmd(cmd_text)
+        self.__push_level()
+        self.cmd_cxt.append("if")
+        return
+
+    def __elif_cmd(self, args):
+        if self.cmd_cxt[-1] != "if":
+            raise UnmatchedBlock(self.lineno(), "elif")
+        directive = args[1]
+        string = args[3]
+        cmd_text = "elif self.get_text(\"%s\") == \"%s\":" % \
+            (directive, string)
+        self.__pop_level()
+        self.__write_cmd_noindex(cmd_text)
+        self.__push_level()
+        return
+
+    # [if-index] commands
+    def __if_index_cmd(self, args):
+        # [if-index KEY is [first|even|odd|last|NUMBER]]
+        #  ~~~0~~~  ~1~  2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~
+        cmdlist = {"first": "if %s_index == 0:",
+                   "even" : "if (%s_index %% 2) == 0:",
+                   "odd"  : "if (%s_index %% 2) != 0:",
+                   "last" : "if %s_index == %s_len - 1:"}
+        key = args[1]
+        cmd = args[3]
+        if len(self.re_number.findall(cmd)) == 1:
+            cmd_text = "if %s_index == %s:" % (key, cmd)
+        elif cmdlist.has_key(cmd):
+            if cmd == "last":
+                cmd_text = cmdlist[cmd] % (key,key)
+            else:
+                cmd_text = cmdlist[cmd] % (key)
+        else:
+            raise InvalidDirective(self.lineno(), ''.join(args))
+        self.__write_cmd(cmd_text)
+        self.__push_level()
+        self.cmd_cxt.append("if-index")
+
+    def __elif_index_cmd(self, args):
+        if self.cmd_cxt[-1] != "if-index":
+            raise UnmatchedBlock(self.lineno(), "elif-index")
+        # [elif-index KEY is [first|even|odd|last|NUMBER]]
+        #  ~~~0~~~  ~1~  2 ~~~~~~~~~~~~~~3~~~~~~~~~~~~
+        cmdlist = {"first": "elif %s_index == 0:",
+                   "even" : "elif (%s_index %% 2) == 0:",
+                   "odd"  : "elif (%s_index %% 2) != 0:",
+                   "last" : "elif %s_index == %s_len - 1:"}
+        key = args[1]
+        cmd = args[3]
+        if len(self.re_number.findall(cmd)) == 1:
+            cmd_text = "elif %s_index == %s:" % (key, cmd)
+        elif cmdlist.has_key(cmd):
+            if cmd == "last":
+                cmd_text = cmdlist[cmd] % (key,key)
+            else:
+                cmd_text = cmdlist[cmd] % (key)
+        else:
+            raise InvalidDirective(self.lineno(), ' '.join(args))
+        self.__pop_level()
+        self.__write_cmd_noindex(cmd_text)
+        self.__push_level()
+
+    # [if-any] command
+    def __if_any_cmd(self, args):
+        directive = args[1]
+        cmd_text = "if self.has_key(\"%s\"):" % (directive)
+        self.__write_cmd(cmd_text)
+        self.__push_level()
+        self.cmd_cxt.append("if-any")
+        return
+
+    def __elif_any_cmd(self, args):
+        if self.cmd_cxt[-1] != "if-any":
+            raise UnmatchedBlock(self.lineno(), "elif-any")
+        directive = args[1]
+        cmd_text = "if self.has_key(\"%s\"):" % (directive)
+        self.__pop_level()
+        self.__write_cmd_noindex(cmd_text)
+        self.__push_level()
+        return
+
+    # [else], [endif] commands
+    def __else_cmd(self, args):
+        if self.cmd_cxt[-1] != "if" and self.cmd_cxt[-1] != "if-index" \
+                and self.cmd_cxt[-1] != "if-any":
+            raise UnmatchedBlock(self.lineno(), "else")
+        self.__pop_level()
+        self.__write_cmd_noindex("else:")
+        self.__push_level()
+        return
+
+    def __endif_cmd(self, args):
+        if self.cmd_cxt[-1] != "if" and self.cmd_cxt[-1] != "if-index" \
+                and self.cmd_cxt[-1] != "if-any":
+            raise UnmatchedBlock(self.lineno(), "endif")
+        self.cmd_cxt.pop()
+        self.__pop_level()
+        return
+    # end of [if] commands
+    #------------------------------------------------------------
+
+    def __print_error(self, e):
+        print "Parse Error: line", e.lineno, "in input data"
+        print "  " + ''.join(nesteditem(e.value))
+        lines = self.template.split("\n")
+        length = len(lines)
+        print "------------------------------------------------------------"
+        for i in range(1,10):
+            l = e.lineno - 6 + i
+            if l > 0 and l < length:
+                print lines[l]
+                if i == 5:
+                    uline = '~'*len(lines[l])
+                    print uline
+        print "------------------------------------------------------------"
+    
+    def del_nl_after_cmd(self):
+        # next text index after command
+        next = self.index + 2
+        if next > self.token_len: return
+        if self.token[next] == None: return
+        text = self.token[next]
+        tlen = len(text)
+        if tlen > 0 and text[0] == '\n':
+            self.token[next] = text[1:]
+            return
+        elif tlen > 0 and text[0] == '\r':
+            self.token[next] = text[1:]
+            return
+        elif tlen > 1 and text[0:2] == '\r\n':
+            self.token[next] = text[2:]
+
+    def lineno(self):
+        l = 1
+        for i in range(self.index):
+            if isinstance(self.token[i], StringType):
+                l += self.token[i].count('\n')
+        for i in range(1, self.index, 3):
+            l += 1
+        return l
+
+
+#------------------------------------------------------------
+# Generator and GeneratorBase classes
+#------------------------------------------------------------
+program = """
+class Generator(GeneratorBase):
+    def __init__(self, token, dict):
+        GeneratorBase.__init__(self, token, dict)
+    def generate(self):
+        try:
+            self.process()
+        except YATException, e:
+            self.print_error(e)
+            sys.exit(-1)
+        return self.text
+
+    def process(self):
+"""
+
+class GeneratorBase:
+    def __init__(self, token, dict):
+        self.token = token
+        self.dicts = [dict]
+        self.index = 0
+        self.text = ""
+
+    def print_error(self, e):
+        print "\nTemplate Generation Error: line", e.lineno, "in input data"
+        print "  " + ''.join(nesteditem(e.value))
+        temp = ""
+        for i, s in enumerate(self.token):
+            if s != None:
+                if i % 3 == 1:
+                    temp += "[" + s + "]\n"
+                else:
+                    temp += s
+        lines = temp.split("\n")
+        length = len(lines)
+        print "------------------------------------------------------------"
+        for i in range(1,10):
+            l = e.lineno - 6 + i
+            if l > 0 and l < length:
+                print lines[l]
+                if i == 5:
+                    uline = '~'*len(lines[l])
+                    print uline
+        print "------------------------------------------------------------"
+        
+    def set_index(self, index):
+        self.index = index
+
+    def push_dict(self, dict):
+        self.dicts.append(dict)
+
+    def pop_dict(self):
+        if len(self.dicts) < 2:
+            raise UnmatchedBlock(self.lineno(), "")
+        self.dicts.pop()
+
+    def write(self, text):
+        self.text += text
+
+    def write_dict(self, keytext):
+        self.write(self.get_text(keytext))
+
+    def write_token(self, index):
+        self.write(self.token[index])
+
+    def lineno(self):
+        cnt = 1
+        for i in range(0, self.index, 3):
+            if self.token[i] != None:
+                cnt += self.token[i].count('\n')
+        # count deleted '\n' after commands
+        for i in range(1, self.index, 3):
+            if self.token[i] != None:
+                cnt += 1
+        return cnt
+                                
+    def get_text(self, keytext):
+        val = self.get_value(keytext)
+        if isinstance(val, StringType):
+            return val
+        if isinstance(val, IntType) or isinstance(val, FloatType):
+            return str(val)
+        raise UnexpectedData(self.lineno(), "\"" + keytext + \
+                                 "\" should have string, int or float value.")
+
+    def get_list(self, keytext):
+        val = self.get_value(keytext)
+        if not isinstance(val, ListType):
+            raise UnexpectedData(self.lineno(),
+                                 "\"" + keytext + "\" should have list value.")
+        return val
+
+    def has_key(self, keytext):
+        try:
+            self.get_value(keytext)
+            return True
+        except NotFound, e:
+            return False
+
+    def get_value(self, keytext):
+        keys = keytext.split('.')
+        for i in range(len(self.dicts) - 1, -1, -1):
+            dict_value = self.get_dict_value(keys, self.dicts[i])
+            if dict_value != None:
+                return dict_value
+        raise NotFound(self.lineno(), keytext) 
+
+    def get_dict_value(self, keys, dict):
+        length = len(keys)
+        d = dict
+        for i in range(length):
+            if isinstance(d, DictType) and d.has_key(keys[i]):
+                d = d[keys[i]]
+            else:
+                return None
+        return d
+
+
+#------------------------------------------------------------
+# Exceptions                                
+#------------------------------------------------------------
+class YATException(Exception):
+    pass
+
+class UnknownError(YATException):
+    def __init__(self, lineno):
+        self.lineno = lineno
+        self.value = "Unknown error."
+
+class UnmatchedBlock(YATException):
+    def __init__(self, lineno, msg):
+        self.lineno = lineno
+        self.value = "Unmatched block error: " + msg
+
+class UnexpectedData(YATException):
+    def __init__(self, lineno, msg):
+        self.lineno = lineno
+        self.value = msg
+
+class NotFinalElement(YATException):
+    def __init__(self, dictkey, dictvalue):
+        self.value = "Specified key is not final element: ",\
+            dictkey, "=>", dictvalue
+
+class InvalidDirective(YATException):
+    def __init__(self, lineno, directive):
+        self.lineno = lineno
+        self.value = "Invalid directive: \"[" + directive + "]\""
+
+class UnmatchedData(YATException):
+    def __init__(self, lineno, description):
+        self.lineno = lineno
+        self.value = "Unmatched data and input: ", description
+
+class NotFound(YATException):
+    def __init__(self, lineno, description):
+        self.lineno = lineno
+        self.value = "Value not found for: \"" + description + "\""
+
+#------------------------------------------------------------
+# other functions
+#------------------------------------------------------------
+def nesteditem(aList):
+    for anItem in aList:
+        if type(anItem)==list:
+            for subitem in nesteditem(anItem):
+                yield subitem
+        else:
+            yield anItem
+
+
+
+if __name__ == "__main__":
+    dict = []
+    template = []
+    #------------------------------------------------------------
+    # Example 0
+    #------------------------------------------------------------
+    dict.append({"a": "This is a",
+                 "b": {"1": "This is b.1",
+                       "2": "This is b.2"}
+                 })
+    template.append("""[a]
+
+[b.1]
+
+[b.2]""")
+
+    #------------------------------------------------------------
+    # Example 1
+    #------------------------------------------------------------
+    dict.append({"list": [0, 1, 2],
+                 "listed_dict": [
+                {"name": "x", "value": "1.0"},
+                {"name": "y", "value": "0.2"},
+                {"name": "z", "value": "0.1"}]})
+    template.append("""[for lst in list]
+[lst],  
+[endfor]
+[for lst in listed_dict]
+[lst.name]: [lst.value]
+
+[endfor]""")
+
+    #------------------------------------------------------------
+    # Example 2
+    #------------------------------------------------------------
+    dict.append({"list": [0,1,2,3,4,5,6,7,8,9,10]})
+    template.append("""[for key in list]
+[if-index key is 3] [key] is hoge!!
+[elif-index key is 6] [key] is foo!!
+[elif-index key is 9] [key] is bar!!
+[elif-index key is first] [key] is first
+[elif-index key is last] Omoro-------!!!!
+[elif-index key is odd] [key] is odd number
+[elif-index key is even] [key] is even number
+[endif]
+[endfor]""")
+
+    #------------------------------------------------------------
+    # Example 3
+    #------------------------------------------------------------
+    dict.append({"key1": "a", "key2": "b"})
+    template.append("""[if key1 is a]
+The key1 is "a".
+[else]
+This key1 is not "a".
+[endif]""")
+
+    #------------------------------------------------------------
+    # Example 4
+    #------------------------------------------------------------
+    dict.append({"key1": "a", "key2": "b"})
+    template.append("""[if-any key1]
+key1 exists.
+[endif][if-any key3]
+key3 exists.
+[else]
+key3 does not exists.
+[endif]""")
+
+    dict.append({})
+    template.append("""
+[[]bracket]
+[# comment]
+""")
+
+    import yaml
+    if len(dict) == len(template):
+        for i in range(len(dict)-1,len(dict)):
+            t = Template(template[i])
+            print "-" * 60
+            print "Example:", i
+            print "-" * 60
+            print "Template:\n"
+            print template[i]
+            print "-" * 60
+            print "Dictionary:\n"
+            print yaml.dump(dict[i], default_flow_style=False)
+            print "-" * 60
+            print "Generated Script:\n"
+            print t.get_script()
+            print "-" * 60
+            print "Generated Text:\n"
+            print t.generate(dict[i])
+            print ""


Property changes on: trunk/OpenRTM-aist-Python/setup.py
___________________________________________________________________
Modified: svn:mergeinfo
   - /branches/RELENG_1_0/OpenRTM-aist-Python/setup.py:345-395
/branches/RELENG_1_1/OpenRTM-aist-Python/setup.py:396-478
   + /branches/RELENG_1_0/OpenRTM-aist-Python/setup.py:345-395
/branches/RELENG_1_1/OpenRTM-aist-Python/setup.py:396-478,495



openrtm-commit メーリングリストの案内