root/ossiedev/trunk/tools/alf/ALF.py @ 10575

Revision 10575, 49.6 KB (checked in by Snyder.Jason, 2 years ago)

removed an absolute path and replaced it with the sdr install path from the alf.cfg file

Line 
1#! /bin/env python
2
3## Copyright 2005, 2006, 2007, 2008 Virginia Polytechnic Institute and State University
4##
5## This file is part of the OSSIE ALF Waveform Application Visualization Environment
6##
7## ALF is free software; you can redistribute it and/or modify
8## it under the terms of the GNU General Public License as published by
9## the Free Software Foundation; either version 2 of the License, or
10## (at your option) any later version.
11##
12## ALF is distributed in the hope that it will be useful, but WITHOUT ANY
13## WARRANTY; without even the implied warranty of
14## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15## GNU General Public License for more details.
16##
17## You should have received a copy of the GNU General Public License
18## along with OSSIE Waveform Developer; if not, write to the Free Software
19## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21import wx
22from wx.lib import ogl
23
24try:   # mac framework
25    from wavedev import ComponentClass as CC
26    from wavedev import WaveformClass
27    import CF, CF__POA
28    import customInterfaces
29    import standardInterfaces
30    import importResource
31    import importIDL
32
33except ImportError:  # 0.6.2
34    from WaveDev.wavedev import ComponentClass as CC
35    from WaveDev.wavedev import WaveformClass
36    import ossie.standardinterfaces.standardInterfaces as standardInterfaces
37    import ossie.custominterfaces.customInterfaces as customInterfaces
38    import ossie.cf.CF as CF
39    import ossie.cf.CF__POA as CF__POA
40    import WaveDev.wavedev.importResource as importResource
41    import WaveDev.wavedev.importIDL as importIDL
42
43from omniORB import CORBA, PortableServer
44import CosNaming
45import sys
46import importWaveform
47import ALFshapes, ALFtiming
48
49import xml.dom.minidom
50from xml.dom.minidom import Node
51
52import os
53import ALFutils
54
55import connectTool
56from namingserviceDialog import NamingserviceDialog
57import compform
58import shutil
59import shlex
60import subprocess
61import ConfigParser
62from ALFNodeBooterUtils import ALFNodeBooterUtils
63from ALFNSChoiceDialog import ALFNSChoiceDialog
64from ALFNodeBooterDialog import ALFNodeBooterDialog
65
66import wx.lib.foldpanelbar as fpb
67
68#----------------------------------------------------------------------
69# Create unique IDs for menu items and toolbar items for associating
70# events with a particular action
71[wxID_TOOLBAR_TIMING_TOOL, wxID_TOOLBAR_REFRESH_TOOL,
72wxID_TOOLBAR_TIMING_DISPLAY_TOOL, wxID_TOOLBAR_CONNECT_TOOL,
73wxID_TOOLBAR_NAMINGSERVICE_DIALOG, wxID_TOOLBAR_LAUNCH_WAVEDASH,
74wxID_TOOLBAR_START_NODEBOOTER] = [wx.NewId() for x in range(7)]
75
76[wxID_NSBOX_POPUP_DISPLAY, wxID_NSBOX_POPUP_START,
77 wxID_NSBOX_POPUP_STOP, wxID_NSBOX_POPUP_UNINSTALL] = [
78                                                 wx.NewId() for x in range(4)]
79
80[wxID_INSTALLBOX_POPUP_INSTALL_START, wxID_COMPONENTSBOX_POPUP_INSTALL_START,
81 wxID_INSTALLBOX_POPUP_INSTALL, wxID_COMPONENTSBOX_POPUP_INSTALL] = [wx.NewId() for x in range(4)]
82
83OSSIE_CONFIG_FILE = '.ossie.cfg'
84#----------------------------------------------------------------------
85class alfApp(wx.App):
86    def OnInit(self):
87        self.main = alfFrame(None)
88        self.main.Show()
89        self.SetTopWindow(self.main)
90        return True
91
92#----------------------------------------------------------------------
93class alfFrame(wx.Frame):
94    def _init_ctrls(self, parent):
95        wx.Frame.__init__(self, id=-1, name='CompFrame',
96            parent=parent, pos=wx.DefaultPosition, size=wx.Size(1100, 770),
97            style=wx.DEFAULT_FRAME_STYLE, title=u'ALF - Waveform Debugger')
98       
99        # Initialize graphics
100        ogl.OGLInitialize()
101        ALFshapes.initializeColours()
102
103        # Create the sash window and layout
104        self._leftWindow = wx.SashLayoutWindow(self, 101, wx.DefaultPosition,
105            wx.Size(240, 600), wx.NO_BORDER | wx.SW_3D | wx.CLIP_CHILDREN)
106           
107        self._leftWindow.SetDefaultSize(wx.Size(300, 400))
108        self._leftWindow.SetOrientation(wx.LAYOUT_VERTICAL)
109        self._leftWindow.SetAlignment(wx.LAYOUT_LEFT)
110        self._leftWindow.SetSashVisible(wx.SASH_RIGHT, True)
111        self._leftWindow.SetExtraBorderSize(10)
112
113        self.ID_WINDOW_TOP = 100
114        self.ID_WINDOW_LEFT = 101
115        self.ID_WINDOW_RIGHT = 102
116        self.ID_WINDOW_BOTTOM = 103
117
118        self._leftWindow.Bind(wx.EVT_SASH_DRAGGED_RANGE, self.OnFoldPanelBarDrag,
119            id=100, id2=103)
120        self.Bind(wx.EVT_SIZE, self.OnFoldPanelSize)
121       
122        # Instantiate the main canvas
123        self.canvas = MainWindow(self, self)
124
125        # Create the fold panel and add its windows
126        self._fpb_pnl = None
127        self.CreateFoldPanel()
128       
129        # Create the status and toolbars
130        self.CreateStatusBar(1, wx.ST_SIZEGRIP)
131        self.CreateToolBar()
132
133        # Make a popup box for the Naming Service / Manage Waveforms functionality
134        self.nsBoxPopup = wx.Menu(title=u'')
135        self.init_nsBoxPopup_Items(self.nsBoxPopup)
136       
137        # Make a popup box for the Launch Waveforms functionality
138        self.installBoxPopup = wx.Menu(title=u'')
139        self.init_installBoxPopup_Items(self.installBoxPopup)
140
141        # Make a popup box for the Launch Components asWaveforms functionality
142        self.componentsBoxPopup = wx.Menu(title=u'')
143        self.init_componentsBoxPopup_Items(self.componentsBoxPopup)
144
145        self.setupToolbar()
146       
147        self.Bind(wx.EVT_CLOSE, self.OnClose)
148        self.connections = {'127.0.0.1': []}
149        self.namingservice = ['127.0.0.1', '']
150        self.nodeBooterProcess = None
151        self.nbUtils = ALFNodeBooterUtils()
152        if not self.nbUtils.namingServiceIsRunning():
153            anscd = ALFNSChoiceDialog(self)
154       
155
156    def __init__(self,parent):
157        self.active_wave = None
158        self.timing_display = None
159        self.tools = None
160        self.connect_frame = None
161        self.waveform_displays = {}
162
163        # WARNING: if alf is restarted and waveforms are left running
164        # counters will overlap and cause a crash :/
165        self.compform_counter = 0
166
167        self._init_ctrls(parent)
168        self.Available_Ints = ALFutils.importStandardIdl(self)
169        self.rootContext = None
170        self.domMgr = None
171        self.fileMgr = None
172       
173       
174        self.init_CORBA()
175       
176        ALFutils.LoadConfiguration(self)
177
178        self.waveformData = {}
179        self.tool_frames = []
180        self.last_waveform_data_update = None
181        self.dasXML_list = []
182        self.availableWaveforms = {}
183        self.availableComponents = {}
184        self.connections = {'127.0.0.1': []}
185
186        if self.rootContext != None and self.fileMgr != None:
187            self.DisplayInstalledWaveforms()
188            self.DisplayAvailableWaveforms()
189            self.DisplayAvailableComponents()
190
191    def init_CORBA(self):
192        """Initialize an orb and try to connect to the DomainManager"""
193
194        try:
195            sys.argv.index('-ORBInitRef')
196        except ValueError:
197            sys.argv.append('-ORBInitRef')
198            sys.argv.append('NameService=corbaname::'+self.namingservice[0])
199           
200        #find the host Ip from the command line args
201        isNSonLocalHost = False
202        for i in range(len(sys.argv)):
203            arg = sys.argv[i]
204            if arg.find("corbaname::") != -1:
205                hostIP = arg[arg.index("::")+2:]
206                if hostIP == '127.0.0.1':
207                    isNSonLocalHost = True
208                    break
209
210        try:
211            self.orb.destroy()
212        except:
213            pass
214
215        self.orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID)
216        self.obj = self.orb.resolve_initial_references("NameService")
217       
218        try:
219            self.rootContext = self.obj._narrow(CosNaming.NamingContext)
220        except:
221            newNS = False
222            while not newNS:
223                ts = "Failed to narrow the root naming context.\n"
224                ts += "Are the Naming Service and nodeBooter running on "+self.namingservice[0]+"?"
225                errorMsg(self, ts)
226                self.namingservice_dialog = NamingserviceDialog(self)
227                if self.namingservice_dialog.GetReturnCode() == 1:
228                    newNS = True
229            return
230       
231        #comp form feature is enabled only when NamingService is running on localhost.
232        if ( isNSonLocalHost is True ):
233            self.componentsBox.Enable(True)
234        else:
235            self.componentsBox.Enable(False)
236            wx.MessageBox("Warning: Comp Form feature will be disabled when naming service is running remotely")
237       
238        if self.rootContext is None:
239            errorMsg(self,"Failed to narrow the root naming context")
240            self.domMgr = None
241            return
242
243        name = [CosNaming.NameComponent("DomainName1",""),
244            CosNaming.NameComponent("DomainManager","")]
245           
246        try:
247            self.obj = self.rootContext.resolve(name)
248        except:
249            errorMsg(self,"DomainManger name not found")
250            self.domMgr = None
251            return
252
253        self.domMgr = self.obj._narrow(CF.DomainManager)
254         #get the reference to FileManager to perform all file operations (list, open etc.. )
255        try:
256            self.fileMgr = self.domMgr._get_fileMgr()
257        except:
258            msg = "init_CORBA(): FATAL Error: Could not get file Manager from Domain manager\n"
259            msg = msg + "Is nodeBooter Running??"
260            errorMsg (self, msg)
261            self.fileMgr = None
262            return
263           
264 
265    #---------------------------------------------------------------
266    # Setup the display
267    #---------------------------------------------------------------
268    def init_nsBoxPopup_Items(self, parent):
269        """Setup the popup menu for the Naming Service / Manage Waveforms box"""
270
271        parent.Append(help='', id=wxID_NSBOX_POPUP_DISPLAY, kind=wx.ITEM_NORMAL,
272                      text=u'Display')
273        self.nsBox.Bind(wx.EVT_MENU, self.OnNsBoxPopupDisplayMenu,
274                        id=wxID_NSBOX_POPUP_DISPLAY)
275       
276        parent.Append(help='', id=wxID_NSBOX_POPUP_START, kind=wx.ITEM_NORMAL,
277                      text=u'Start')
278        self.nsBox.Bind(wx.EVT_MENU, self.OnNsBoxPopupStartMenu,
279                        id=wxID_NSBOX_POPUP_START)
280
281        parent.Append(help='', id=wxID_NSBOX_POPUP_STOP, kind=wx.ITEM_NORMAL,
282                      text=u'Stop')
283        self.nsBox.Bind(wx.EVT_MENU, self.OnNsBoxPopupStopMenu,
284                        id=wxID_NSBOX_POPUP_STOP)
285
286        parent.Append(help='', id=wxID_NSBOX_POPUP_UNINSTALL, kind=wx.ITEM_NORMAL,
287                      text=u'Uninstall')
288        self.nsBox.Bind(wx.EVT_MENU, self.OnNsBoxPopupUninstallMenu,
289                        id=wxID_NSBOX_POPUP_UNINSTALL)
290   
291    def init_installBoxPopup_Items(self, parent):
292        """Setup the popup menu for the Launch Waveforms box"""
293
294        parent.Append(help='', id=wxID_INSTALLBOX_POPUP_INSTALL_START,
295                        kind=wx.ITEM_NORMAL, text=u'Install and Start')
296        self.installBox.Bind(wx.EVT_MENU, self.OnInstallBoxPopupInstallStartMenu,
297                        id=wxID_INSTALLBOX_POPUP_INSTALL_START)
298
299        parent.Append(help='', id=wxID_INSTALLBOX_POPUP_INSTALL,
300                        kind=wx.ITEM_NORMAL, text=u'Install')
301        self.installBox.Bind(wx.EVT_MENU, self.OnInstallBoxPopupInstallMenu,
302                        id=wxID_INSTALLBOX_POPUP_INSTALL)
303       
304    def init_componentsBoxPopup_Items(self, parent):
305        """Setup the popup menu for the Launch Components as Waveforms box"""
306
307        parent.Append(help='', id=wxID_COMPONENTSBOX_POPUP_INSTALL_START,
308                        kind=wx.ITEM_NORMAL, text=u'Install and Start')
309        self.componentsBox.Bind(wx.EVT_MENU, self.OnComponentsBoxPopupInstallStartMenu,
310                        id=wxID_COMPONENTSBOX_POPUP_INSTALL_START)
311
312        parent.Append(help='', id=wxID_COMPONENTSBOX_POPUP_INSTALL,
313                        kind=wx.ITEM_NORMAL, text=u'Install')
314        self.componentsBox.Bind(wx.EVT_MENU, self.OnComponentsBoxPopupInstallMenu,
315                        id=wxID_COMPONENTSBOX_POPUP_INSTALL)
316 
317    def CreateFoldPanel(self):
318        self._fpb_pnl = fpb.FoldPanelBar(self._leftWindow, -1, wx.DefaultPosition,
319            wx.Size(-1,-1), 0)
320       
321        # Create the image list for the fold button icons
322        Images = wx.ImageList(16,16)
323        Images.Add(ALFutils.GetExpandedIconBitmap())
324        Images.Add(ALFutils.GetCollapsedIconBitmap())
325           
326        # Add the Launch Waveforms box
327        item = self._fpb_pnl.AddFoldPanel("Launch Waveform Applications",
328                                          collapsed=False,
329                                          foldIcons=Images)
330        self.installBox = wx.TreeCtrl(name=u'installBox',
331                                      parent=item,
332                                      size = wx.Size(-1,200),
333                                      style = wx.TR_HIDE_ROOT |
334                                              wx.TR_HAS_BUTTONS |
335                                              wx.SIMPLE_BORDER)
336        self._fpb_pnl.AddFoldPanelWindow(item, self.installBox,
337                                         fpb.FPB_ALIGN_WIDTH, 4)
338        self.installBox.Bind(wx.EVT_RIGHT_UP, self.OnInstallBoxRightUp)
339        self.installBox.Bind(wx.EVT_LEFT_DCLICK, self.OnInstallBoxLeftDclick)
340
341        # Add the Launch Components as Waveforms box
342        item = self._fpb_pnl.AddFoldPanel("Launch Components as Applications",
343                                          collapsed=False,
344                                          foldIcons=Images)
345        self.componentsBox = wx.TreeCtrl(name=u'componentsBox',
346                                         parent=item,
347                                         size = wx.Size(-1,200),
348                                         style = wx.TR_HIDE_ROOT |
349                                                 wx.TR_HAS_BUTTONS |
350                                                 wx.SIMPLE_BORDER)
351        self._fpb_pnl.AddFoldPanelWindow(item, self.componentsBox,
352                                         fpb.FPB_ALIGN_WIDTH, 4)
353        self.componentsBox.Bind(wx.EVT_RIGHT_UP, self.OnComponentsBoxRightUp)
354        self.componentsBox.Bind(wx.EVT_LEFT_DCLICK,
355                                self.OnComponentsBoxLeftDclick)
356
357        # Add the Manage Waveforms box
358        item = self._fpb_pnl.AddFoldPanel("Manage Applications",
359                                          collapsed=False,
360                                          foldIcons=Images)
361        self.nsBox = wx.TreeCtrl(name=u'nsBox', parent=item,
362                                 size = wx.Size(-1,200),
363                                 style = wx.TR_HIDE_ROOT |
364                                         wx.TR_HAS_BUTTONS |
365                                         wx.SIMPLE_BORDER)
366        self.nsBox.Bind(wx.EVT_RIGHT_UP, self.OnNsBoxRightUp)
367        self.nsBox.Bind(wx.EVT_LEFT_DCLICK, self.OnNsBoxLeftDclick)
368        self._fpb_pnl.AddFoldPanelWindow(item, self.nsBox,
369                                         fpb.FPB_ALIGN_WIDTH, 4)
370
371        self._leftWindow.SizeWindows()
372       
373       
374    def setupToolbar(self):
375        toolbar = self.GetToolBar()
376        tsize = (20,20)
377        test_bmp = wx.ArtProvider.GetBitmap(wx.ART_REDO, wx.ART_TOOLBAR, tsize)
378        toolbar.AddSimpleTool(wxID_TOOLBAR_REFRESH_TOOL,test_bmp,shortHelpString="Refresh")
379        toolbar.AddSeparator()
380
381        root = __file__
382        if os.path.islink (root):
383            root = os.path.realpath (root)
384        root = os.path.dirname (os.path.abspath (root))
385
386        time_img = wx.Image(root + '/images/timing.png',type=wx.BITMAP_TYPE_PNG)
387        time_img.Rescale(24,24)
388        time_bmp = wx.BitmapFromImage(time_img)
389        toolbar.AddCheckTool(wxID_TOOLBAR_TIMING_TOOL,time_bmp,shortHelp="Enable Timing")
390        self.timing_view_state = False
391
392        time_img = wx.Image(root + '/images/timing_display.png',type=wx.BITMAP_TYPE_PNG)
393        time_img.Rescale(24,24)
394        time_bmp = wx.BitmapFromImage(time_img)
395        toolbar.AddCheckTool(wxID_TOOLBAR_TIMING_DISPLAY_TOOL,time_bmp,shortHelp="Toggle Timing Display")
396       
397        toolbar.AddSeparator()
398
399
400        connect_bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_TOOLBAR, tsize)
401        toolbar.AddSimpleTool(wxID_TOOLBAR_CONNECT_TOOL,connect_bmp,shortHelpString="Connect Tool")
402
403        toolbar.AddSeparator()
404
405        net_img = wx.Image(root + '/images/network.png',type=wx.BITMAP_TYPE_PNG)
406        net_img.Rescale(24,24)
407        net_bmp = wx.BitmapFromImage(net_img)
408        toolbar.AddSimpleTool(wxID_TOOLBAR_NAMINGSERVICE_DIALOG,net_bmp,shortHelpString="Select Naming Service")
409       
410        toolbar.AddSeparator()
411        wavedash_img = wx.Image(root + '/images/launch_wavedash.png', type=wx.BITMAP_TYPE_PNG)
412        wavedash_img.Rescale(24,24)
413        wavedash_bmp = wx.BitmapFromImage(wavedash_img)
414        toolbar.AddSimpleTool(wxID_TOOLBAR_LAUNCH_WAVEDASH, wavedash_bmp, shortHelpString="Launch Wavedash to configure waveforms")
415
416        toolbar.AddSeparator()
417        nodeBooter_img = wx.Image(root + '/images/nbstart.png', type = wx.BITMAP_TYPE_PNG)
418        nodeBooter_img.Rescale(24, 24)
419        nodeBooter_bmp = wx.BitmapFromImage(nodeBooter_img)
420        toolbar.AddSimpleTool(wxID_TOOLBAR_START_NODEBOOTER, nodeBooter_bmp, shortHelpString="Start NodeBooter")
421        toolbar.Bind(wx.EVT_TOOL, self.OnToolBarClick)
422       
423        toolbar.Realize()
424
425    # ---------------------------------------------------
426    # Event handling for toolbar
427    # ---------------------------------------------------
428    def OnToolBarClick(self,event):
429        tb = self.GetToolBar()
430        if event.GetId() == wxID_TOOLBAR_TIMING_TOOL:
431            if tb.GetToolState(wxID_TOOLBAR_TIMING_TOOL):
432                if self.active_wave == None:
433                    errorMsg(self,"Please select and display a waveform first!")       
434                    tb.ToggleTool(wxID_TOOLBAR_TIMING_TOOL, False)
435                    return
436                tb.EnableTool(wxID_TOOLBAR_TIMING_DISPLAY_TOOL, True)
437                tb.SetToolShortHelp(wxID_TOOLBAR_TIMING_TOOL, "Disable Timing")
438                self.timing_display = ALFtiming.TimingDisplay(self.active_wave.naming_context, self)
439            else:
440                self.timing_display = None
441                tb.EnableTool(wxID_TOOLBAR_TIMING_DISPLAY_TOOL, False)
442                tb.SetToolShortHelp(wxID_TOOLBAR_TIMING_TOOL, "Enable Timing")
443                self.refreshDisplay()
444
445        if event.GetId() == wxID_TOOLBAR_TIMING_DISPLAY_TOOL:
446            if tb.GetToolState(wxID_TOOLBAR_TIMING_DISPLAY_TOOL):
447                tb.SetToolShortHelp(wxID_TOOLBAR_TIMING_DISPLAY_TOOL, "Disable Timing Graphics")
448                self.timing_view_state = True
449            else:
450                tb.SetToolShortHelp(wxID_TOOLBAR_TIMING_DISPLAY_TOOL, "Enable Timing Graphics")
451                self.timing_view_state = False
452
453        elif event.GetId() == wxID_TOOLBAR_CONNECT_TOOL:
454            if self.connect_frame:
455                self.connect_frame.Raise()
456            else:
457                self.connect_frame = connectTool.create(self)
458
459        elif event.GetId() == wxID_TOOLBAR_NAMINGSERVICE_DIALOG:
460            self.namingservice_dialog = NamingserviceDialog(self)
461           
462        elif event.GetId() == wxID_TOOLBAR_LAUNCH_WAVEDASH:
463            namingService = "-ORBInitRef NameService=corbaname::" + self.namingservice[0]
464            if (os.path.exists("/usr/local/bin/WAVEDASH")):
465                os.spawnl(os.P_NOWAIT, "/usr/local/bin/WAVEDASH", namingService, "")
466            elif (os.path.exists("/usr/bin/WAVEDASH")):
467                os.spawnl(os.P_NOWAIT, "/usr/bin/WAVEDASH", namingService, "")
468            else:
469                errorMsg(self, "Failed to launch WAVEDASH. Executable(WAVEDASH) not found in /usr/local/bin/ and /usr/bin/ !!!")
470                return
471
472
473        # Refresh the display: Naming Service, Waveform List, and Canvas
474        elif event.GetId() == wxID_TOOLBAR_REFRESH_TOOL:
475            self.refreshDisplay(True)
476            self.DisplayInstalledWaveforms()
477            self.DisplayAvailableWaveforms()
478            self.DisplayAvailableComponents()
479            tb.ToggleTool(wxID_TOOLBAR_REFRESH_TOOL, False)
480       
481        elif event.GetId() == wxID_TOOLBAR_START_NODEBOOTER:
482            anbd = ALFNodeBooterDialog(self)
483           
484            if anbd.GetReturnCode() == 0:
485                self.namingservice[0] = '127.0.0.1'
486                self.init_CORBA()
487                self.refreshDisplay(True)
488                self.DisplayInstalledWaveforms()
489                self.DisplayAvailableWaveforms()
490                self.DisplayAvailableComponents()
491           
492    def processTimingEvent(self, component_name, port_name, function_name, description, time_s, time_us, number_samples):
493        if self.active_wave == None or (self.active_wave.naming_context not in component_name):
494            errorMsg(self,"Cannot find waveform containing: " + component_name)
495
496        cname = component_name[component_name.rfind('/')+1:]
497        if self.active_wave != None:
498            for comp in self.active_wave.components:
499                if comp.name == cname:
500                    comp.shape.processTimingEvent(port_name, function_name, description, time_s, time_us, number_samples)
501
502
503       
504    # ---------------------------------------------------------
505    # Event handling for the FoldPanel
506    # --------------------------------------------------------
507    def OnFoldPanelSize(self, event):
508        wx.LayoutAlgorithm().LayoutWindow(self, self.canvas)
509        event.Skip()
510   
511    def OnFoldPanelBarDrag(self, event):
512        if event.GetDragStatus() == wx.SASH_STATUS_OUT_OF_RANGE:
513            return
514               
515        if event.GetId() == self.ID_WINDOW_LEFT:
516            self._leftWindow.SetDefaultSize(wx.Size(event.GetDragRect().width, 400))
517               
518        # Leaves bits of itself behind sometimes
519        wx.LayoutAlgorithm().LayoutWindow(self, self.canvas)
520        self.canvas.Refresh()
521           
522        event.Skip()
523
524    # ---------------------------------------------------------
525    # Event handling for Naming Service / Manage Waveforms box
526    # --------------------------------------------------------
527    def OnNsBoxRightUp(self, event):
528        self.nsBox.PopupMenu(self.nsBoxPopup)
529        event.Skip()
530
531    def OnNsBoxLeftDclick(self, event):
532        self.DisplayWaveform()
533        event.Skip()
534
535    def OnNsBoxPopupDisplayMenu(self, event):
536        self.DisplayWaveform()
537        event.Skip()
538
539    def OnNsBoxPopupStartMenu(self, event):
540        self.StartApplication()
541        event.Skip()
542
543    def OnNsBoxPopupStopMenu(self, event):
544        self.StopApplication()
545        event.Skip()
546
547    def OnNsBoxPopupUninstallMenu(self, event):
548        self.UninstallWaveform()
549        event.Skip()
550
551    def DisplayWaveform(self):
552        sn = self.nsBox.GetSelection()
553        if sn == self.nsBox.GetRootItem():
554            errorMsg(self,'Please select a waveform!')
555            return
556        snPrnt = self.nsBox.GetItemParent(sn)
557        if snPrnt != self.nsBox.GetRootItem():
558            errorMsg(self,'Please select a waveform!')
559            return
560
561        wave_name = self.nsBox.GetItemText(sn)
562        app = self.nsBox.GetPyData(sn)
563        if app is None:
564            errorMsg(self,'No application associated with this entry!')
565            return
566           
567        # Check to see if a waveform is already active
568        if self.active_wave != None:
569            self.refreshDisplay(True)
570
571        # Set item bold and all others set to plain text
572        troot = self.nsBox.GetRootItem()
573        if self.nsBox.GetChildrenCount(troot) <= 0:
574            return
575        cid1,cookie1 = self.nsBox.GetFirstChild(troot)
576        self.nsBox.SetItemBold(cid1, False)
577        for x in range(self.nsBox.GetChildrenCount(troot,recursively=False)-1):
578            cid2,cookie2 = self.nsBox.GetNextChild(troot,cookie1)
579            self.nsBox.SetItemBold(cid2, False)
580            cid1 = cid2
581            cookie1 = cookie2
582
583        self.nsBox.SetItemBold(sn, True)
584        self.nsBox.SelectItem(sn, False)
585
586        # Check to see if this waveform has previously been displayed
587        # If so, then update the display and return
588        if self.waveform_displays.has_key(wave_name):
589            # Clear the canvas and get ready to display the waveform
590            #print "already imported this waveform .... displaying..."
591            tmpdisplay = self.waveform_displays[wave_name]
592#            self.refreshDisplay(True)
593            self.active_wave = tmpdisplay.waveform
594            self.canvas.updateDisplay(tmpdisplay)
595            return
596
597# NOTE: use CF::FileManager list to find SAD file
598#sadfile wud resemble like "/waveforms/ossie_demo/ossie_demo.sad.xml
599        sadfile = app._get_profile()
600        sadfile = sadfile.replace('//','')
601        wav_name = sadfile.replace('.sad.xml','')
602# No need to prepend /sdr/dom to sad file. CF:FileManager takes the relative path.
603        #sadpath = '/sdr/dom/' + sadfile
604        sadpath = sadfile
605
606        self.active_wave = importWaveform.getWaveform(sadpath, self, self.Available_Ints)
607        self.active_wave.naming_context = str(wave_name)
608
609        tmpdisplay = self.AddWaveformShape(self.active_wave)
610        self.waveform_displays[wave_name] = tmpdisplay
611
612        self.canvas.updateDisplay(tmpdisplay)
613
614           
615    def DisplayInstalledWaveforms(self):
616        self.nsBox.DeleteAllItems()
617        nsRoot = self.nsBox.AddRoot("ns_root")
618       
619        if self.domMgr == None or self.rootContext == None:
620            return
621
622        dom_obj = self.rootContext.resolve([CosNaming.NameComponent("DomainName1","")])
623        dom_context = dom_obj._narrow(CosNaming.NamingContext)
624        if dom_context is None:
625            return
626
627        try:
628            appSeq =  self.domMgr._get_applications()
629        except:
630            newNS = False
631            while not newNS:
632                ts = 'Could not got a list of applications from the domain manager. Is nodeBooter running on this system?'
633                errorMsg(self, ts)
634                self.namingservice_dialog = NamingserviceDialog(self)
635                if self.namingservice_dialog.GetReturnCode() == 1:
636                    newNS = True
637            return
638
639
640        members = dom_context.list(1000)
641        for m in members[0]:
642            wav_name = str(m.binding_name[0].id)
643            wav_obj = dom_context.resolve([CosNaming.NameComponent(wav_name,"")])
644            wav_context = wav_obj._narrow(CosNaming.NamingContext)
645            if wav_context is None:
646                continue
647
648            contextApp = None
649            foundApp = False
650            for app in appSeq:
651                compNameCon = app._get_componentNamingContexts()
652                for compElementType in  compNameCon:
653                    if wav_name in compElementType.elementId:
654                        waveformApp = app
655                        foundApp = True
656                        #print compElementType.componentId + " " + compElementType.elementId
657                        break
658
659            if not foundApp:
660                print "Could not find associated application for: " + wav_name
661                continue
662
663            t1 = self.nsBox.AppendItem(nsRoot,wav_name)
664            self.nsBox.SetPyData(t1,waveformApp)
665           
666            # Set item bold if it is the active waveform
667            if self.active_wave is not None:
668                if self.active_wave.naming_context == wav_name:
669                    self.nsBox.SetItemBold(t1, True)
670                   
671        self.nsBox.SortChildren(nsRoot)
672
673    # ---------------------------------------------------------
674    # Event handling and control for Launch Waveforms box
675    # --------------------------------------------------------
676    def DisplayAvailableWaveforms(self):
677        self.installBox.DeleteAllItems()
678        self.availableWaveforms.clear()
679        installRoot = self.installBox.AddRoot("install_root")
680       
681       
682        sadFileObjList = self.fileMgr.list("/*.sad.xml")
683        dasFileObjList = self.fileMgr.list("/*_DAS.xml")
684       
685        #if SAD and DAS file count differ, then report error
686        if len(sadFileObjList) != len(dasFileObjList):
687            errorMsg(self, "Mismatch in SAD and DAS files")
688           
689
690        for fIndex in range(len(sadFileObjList)):
691            sadObj = sadFileObjList[fIndex]
692            dasObj = dasFileObjList[fIndex]
693           
694            #get SAD and DAS file names
695            #the file name is stored as an absolute path to the FileManager file system
696            #e.g file name = dom/waveforms/ossie_demo/ossie_demo.sad.xml
697            #throughout ALF,we store the filenames in the model as relative to the
698            #FileManager root dir (/sdr/dom). Hence strip off dom/ from the object filename
699       
700            sad_file = sadObj.name[sadObj.name.find("/"):]
701            das_file = dasObj.name[dasObj.name.find("/"):]
702            #e.g. sad_file = /xml/waveforms/ossie_demo/ossie_demo.sad.xml
703            #we need to extract the waveform name part from the above file name
704            #find the position of the rightmost "/" and extract the substring till
705            #last 8 chars (that corresponds to .spd.xml).
706            wavename = sad_file[sad_file.rfind("/")+1:-8]
707           
708            #make sure that both SAD and DAS files are in the same directory
709            #remove the file name alone and compare the directory paths of SAD and DAS file
710            if ( sad_file[:sad_file.rfind("/")] != das_file[:das_file.rfind("/")] ):
711                errorMsg(self, "Invalid SAD or DAS file - " + sad_file + " " + das_file )
712                continue
713            if ( das_file.find(wavename) == -1 ):
714                errorMsg (self, "SAD and DAS files mismatch")
715                continue
716           
717            #self.installpath is set to /sdr/dom by default
718            full_sad_file = self.installPath + sad_file
719            full_das_file = self.installPath + das_file
720     
721           
722            if (not self.availableWaveforms.has_key(wavename)):
723                self.availableWaveforms[wavename] = (sad_file, full_sad_file, das_file, full_das_file)
724            else:
725                #duplicate waveforms found
726                errorMsg(self, "Duplicate " + wavename + " waveform found\n")
727                continue
728           
729        # Populate the display at the Domain level
730        for waveform in self.availableWaveforms.keys():
731            t1 = self.installBox.AppendItem(installRoot,waveform)
732            self.installBox.SetPyData(t1,self.availableWaveforms[waveform])
733            self.installBox.SetItemBold(t1,False)
734
735        self.installBox.SortChildren(installRoot)
736
737
738    # -----------------------------------------------------------------
739    # Event handling and control for Launch Components as Waveforms box
740    # -----------------------------------------------------------------
741    def DisplayAvailableComponents(self):
742        self.componentsBox.DeleteAllItems()
743        self.availableComponents.clear()
744        installRoot = self.componentsBox.AddRoot("install_root")
745       
746        #get the list of spd files under /sdr/dom/xml
747        spdFiles = ALFutils.getFileList(self.fileMgr, "dom/xml", "*.spd.xml")
748        for spd_file in spdFiles:   
749             compname = spd_file[spd_file.rfind("/")+1:-8]
750             #installPath is set to /sdr/dom by default
751             compNameAndDir = spd_file[:spd_file.rfind("/")]
752
753             if self.availableComponents.has_key(compname):
754                 errorMsg(self, "Conflicting component name: " + compname)
755                 continue
756           
757             self.availableComponents[compname] = (compname, compNameAndDir)
758   
759        # Populate the display at the Domain level
760        for component in self.availableComponents.keys():
761            t1 = self.componentsBox.AppendItem(installRoot,component)
762            self.componentsBox.SetPyData(t1,self.availableComponents[component])
763            self.componentsBox.SetItemBold(t1,False)
764
765        self.componentsBox.SortChildren(installRoot)
766
767
768    def OnInstallBoxRightUp(self, event):
769        self.installBox.PopupMenu(self.installBoxPopup)
770        event.Skip()
771   
772    def OnInstallBoxPopupInstallMenu(self, event):
773        self.InstallWaveformFromBox(False)
774        event.Skip()
775       
776    def OnInstallBoxPopupInstallStartMenu(self, event):
777        self.InstallWaveformFromBox(True)
778        event.Skip()
779
780    def OnInstallBoxLeftDclick(self, event):
781        self.InstallWaveformFromBox(True)
782        event.Skip()
783
784    def OnComponentsBoxRightUp(self, event):
785        self.componentsBox.PopupMenu(self.componentsBoxPopup)
786        event.Skip()
787
788    def OnComponentsBoxPopupInstallMenu(self, event):
789        ''' Install but do not start compform '''
790        self.InstallCompform(False)
791        event.Skip()
792
793    def OnComponentsBoxPopupInstallStartMenu(self, event):
794        ''' Install and start the selected compform '''
795        self.InstallCompform(True)
796        event.Skip()
797
798    def OnComponentsBoxLeftDclick(self, event):
799        ''' Install and start the selected compform '''
800        self.InstallCompform(True)
801        event.Skip()
802
803    def InstallWaveformFromBox(self, start_flag):
804        selection = self.installBox.GetSelection()
805        name_SAD, absolute_name_SAD, name_DAS, absolute_name_DAS = self.installBox.GetPyData(selection)
806
807        self.InstallWaveform(name_SAD, absolute_name_SAD,
808                             name_DAS, absolute_name_DAS, start_flag)
809
810
811    def InstallWaveform(self,name_SAD, absolute_name_SAD,
812                        name_DAS, absolute_name_DAS, start_flag = True):
813        ''' Installs waveform application as an (SCA) application.  By default
814            the (SCA) application will be started '''
815         
816        #name_SAD - contains the path of the SAD file relative the framework filesystem
817        #e.g. the framework file system is mounted at /sdr/dom. then the value of name_SAD
818        #would be /waveforms/ossie_demo/ossie_demo.sad.xml
819           
820        #doc_sad = xml.dom.minidom.parse(absolute_name_SAD)
821        doc_sad = ALFutils.getDOM (self.fileMgr, name_SAD)
822        if doc_sad is None:
823            return
824        app_name = doc_sad.getElementsByTagName("softwareassembly")[0].getAttribute("name")
825        _appFacProps = []
826        devMgrSeq = self.domMgr._get_deviceManagers()
827        available_dev_seq = []
828        for devmgr in range(len(devMgrSeq)):
829            devMgr = devMgrSeq[devmgr]
830            curr_devSeq = devMgr._get_registeredDevices()
831            for dev in range(len(curr_devSeq)):
832                curr_dev = curr_devSeq[dev]
833                available_dev_seq.append(curr_dev._get_identifier())
834                #print curr_dev._get_identifier()
835
836        self.domMgr.installApplication(name_SAD)
837       
838        # Parse the device assignment sequence, ensure
839        #Use FileManager to open files.
840       
841        doc_das = ALFutils.getDOM(self.fileMgr, name_DAS)
842        deviceassignmenttypeNodeList = doc_das.getElementsByTagName("deviceassignmenttype")
843
844        for deviceassignmenttypeNode in deviceassignmenttypeNodeList:
845            # look for assigndeviceid nodes
846            assigndeviceidNodeList = deviceassignmenttypeNode.getElementsByTagName("assigndeviceid")
847            if len(assigndeviceidNodeList) == 0:
848                ts = "Could not find \"assigndeviceid\" tag\nAborting install"
849                errorMsg(self, ts)
850                return
851
852            # get assigndeviceid tag value (DCE:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
853            assigndeviceid = assigndeviceidNodeList[0].firstChild.data
854
855            # ensure assigndeviceid is in list of available devices
856            if assigndeviceid not in available_dev_seq:
857                ts = "Could not find the required device: " + str(assigndeviceid)
858                ts += "\nAborting install"
859                errorMsg(self, ts)
860                return
861               
862        _devSeq = self.BuildDevSeq(name_DAS)
863        _applicationFactories = self.domMgr._get_applicationFactories()
864
865        # attempt to match up the waveform application name to
866        # a application factory of the same name
867        app_factory_num = -1
868        for app_num in range(len(_applicationFactories)):
869            if _applicationFactories[app_num]._get_name()==app_name:
870                app_factory_num = app_num
871                break
872   
873        if app_factory_num == -1:
874            print "Application factory not found"
875            sys.exit(-1)
876
877        # use the application factor I found above to create an instance
878        # of an application
879        try:
880            app = _applicationFactories[app_factory_num].create(_applicationFactories[app_factory_num]._get_name(),_appFacProps,_devSeq)
881        except:
882            print "Unable to create application - make sure that all appropriate nodes are installed"
883            return(None)
884       
885        if start_flag:
886            # start the application
887            app.start()
888       
889        naming_context_list = app._get_componentNamingContexts()
890        naming_context = naming_context_list[0].elementId.split("/")
891        application_name = app._get_name()
892        waveform_name = naming_context[1]
893       
894       
895#        self.refreshDisplay()
896        self.DisplayInstalledWaveforms()
897        if self.connect_frame:
898            self.connect_frame.refreshDisplay()
899
900        return app
901
902    def InstallCompform(self, start_flag = False):
903        ''' This method will take the component selected from the GUI
904            and create the necessary files to define a Waveform Application
905            consisting of a single instance of this component.  The files will
906            then be passed to the InstallWaveform method which will create
907            an (SCA) application from the Waveform Application.   '''
908
909
910        print "WARNING: if your node's GPP UUID is not DCE:5ba336ee-aaaa-aaaa-aaaa-00123f573a7f this will not work...\n"
911        # get component name from the list
912        selection = self.componentsBox.GetSelection()
913        compName, compNameAndDir = self.componentsBox.GetPyData(selection)
914
915        self.compform_counter = self.compform_counter + 1
916
917        tmp_dir_name = "/_tmp_alf_waveforms/"  # this is where I put my temporary
918                                              # xml files
919        tmp_wave_name = "_" + compName + str(self.compform_counter)
920
921
922        #make the directory to put the XML
923        if self.fileMgr.exists(tmp_dir_name) == False:
924            try:
925                #for some weird reasons, fileMgr.exists(...) looks by default in /sdr/dom/
926                #but mkdir(...) creates a directory under /sdr/dev :-(
927                #as a temp fix, use "dom/_tmp_alf_waveforms"
928                print "creating _tmp_alf_waveforms directory\n"
929                self.fileMgr.mkdir("dom" + tmp_dir_name)   
930            except:
931                errorMsg(self,"Cannot create temporary directory in the waveform directory.\n"
932                              "You may need to change the temporary directory to one that you have write permissions to")
933       
934        #Ticket 272:could not create a second instance of a component as a waveform if ALF is restarted.   
935        #Fix: loop into _tmp_alf_waveforms/ directory and see if tmp waveforms exists already
936        #with the same name. If found, increment the counter and form a new name for the temp
937        #waveform. Repeat this until you find a new name.
938        while (self.fileMgr.exists(tmp_dir_name + tmp_wave_name) == True ):
939            print "InstallCompform(): ", tmp_wave_name + " exists already...Regenerating new name ", "at ", tmp_dir_name
940            self.compform_counter = self.compform_counter + 1
941            tmp_wave_name = "_" + compName + str(self.compform_counter)
942
943        if self.fileMgr.exists(tmp_dir_name + tmp_wave_name) == False:   
944            try:
945                #Add "dom" to the directory because of the above said weird reasons
946                print tmp_dir_name, tmp_wave_name
947                self.fileMgr.mkdir("dom" + tmp_dir_name + tmp_wave_name)
948               
949            except:
950                errorMsg(self,"Cannot create temporary directory in the waveform directory.\n"
951                              "You may need to change the temporary directory to one that you have write permissions to")
952                return
953               
954               
955        #till this place, all file related operations are done through framework fileManager
956        #generating temp compform files is done by Wavedev code. hence, passing the sdr install
957        #path of the component files that should be in config/alf.cfg under installpath
958        my_compform = compform.compform(compName, self.installPath + '/' +compNameAndDir,
959                                        self.installPath + '/' +tmp_dir_name, tmp_wave_name)
960        my_compform.create()
961
962
963        print "WARNING: tmp files generated in " + tmp_dir_name
964
965        tmp_dir_name =  tmp_dir_name +  tmp_wave_name + "/"
966       
967        self.DisplayAvailableWaveforms()
968        #the second and fourth arguments are kind of redundant. but passing to keep inline
969        #with the previous version of this code. can be removed in future.
970        self.InstallWaveform(tmp_dir_name + tmp_wave_name + ".sad.xml",
971                             tmp_dir_name + tmp_wave_name + ".sad.xml",
972                             tmp_dir_name + tmp_wave_name + "_DAS.xml",
973                             tmp_dir_name + tmp_wave_name + "_DAS.xml",
974                             start_flag)
975       
976    def StartApplication(self):
977        selection = self.nsBox.GetSelection()
978        app_ref = self.nsBox.GetPyData(selection)
979        app_ref.start()
980        self.DisplayInstalledWaveforms()
981
982
983    def StopApplication(self):
984        selection = self.nsBox.GetSelection()
985        app_ref = self.nsBox.GetPyData(selection)
986        app_ref.stop()
987        self.DisplayInstalledWaveforms()
988
989    def UninstallWaveform(self):
990        selection = self.nsBox.GetSelection()
991        waveform_name = self.nsBox.GetItemText(selection)
992        if self.active_wave is not None:
993            if self.active_wave.naming_context == waveform_name:
994                self.refreshDisplay(True)
995        if self.waveform_displays.has_key(waveform_name):
996            # close any tool frames associated with waveform display
997            tmp_display = self.waveform_displays[waveform_name]
998            while len(tmp_display.tool_frames) > 0:
999                tf = tmp_display.tool_frames.pop()
1000                tf.Close()
1001            self.waveform_displays.pop(waveform_name)
1002        app_ref = self.nsBox.GetPyData(selection)
1003#        self.domMgr.uninstallApplication(app_ref._get_identifier()) # not sure if we need this or not
1004
1005        # Remove any connections we made with the connect tool to/from this waveform
1006        for connection in reversed(self.connections[self.namingservice[0]]):
1007            if waveform_name in connection['appNames']:
1008                try:
1009                    resourceRef = self.rootContext.resolve(connection['name'])
1010                    resourceHandle = resourceRef._narrow(CF.Resource)
1011                    portReference = resourceHandle.getPort(connection['port'])
1012                    portHandle = portReference._narrow(CF.Port)
1013                    portHandle.disconnectPort(connection['id'])
1014                    self.connections[self.namingservice[0]].remove(connection)
1015                except e:
1016                    print e
1017                    dial = wx.MessageDialog(self, 'Disconnect failed.', 'Failed', wx.OK)
1018                    dial.ShowModal()
1019
1020
1021        app_ref.releaseObject()
1022#        self.refreshDisplay()
1023        self.DisplayInstalledWaveforms()
1024
1025        if self.connect_frame:
1026            self.connect_frame.refreshDisplay()
1027
1028
1029    def BuildDevSeq(self, dasXML):
1030        doc_das = ALFutils.getDOM(self.fileMgr, dasXML)
1031        if doc_das is None:
1032            return None
1033        # create node list of "deviceassignmenttype"
1034        deviceassignmenttypeNodeList = doc_das.getElementsByTagName("deviceassignmenttype")
1035
1036        ds = []
1037        for n in deviceassignmenttypeNodeList:
1038            componentid = n.getElementsByTagName("componentid")[0].firstChild.data
1039            assigndeviceid = n.getElementsByTagName("assigndeviceid")[0].firstChild.data
1040            ds.append(CF.DeviceAssignmentType(str(componentid),str(assigndeviceid)))
1041
1042        return ds
1043   
1044
1045    #----------------------------------------------------------------------------
1046    # Waveform level controls and functions
1047    #----------------------------------------------------------------------------
1048    def refreshDisplay(self, init = False):
1049#        self.DisplayInstalledWaveforms()
1050       
1051        dc = wx.ClientDC(self.canvas)
1052        self.canvas.PrepareDC(dc)
1053
1054        if init:
1055            if self.active_wave != None and self.timing_view_state:
1056                for comp in self.active_wave.components:
1057                    for gauge in comp.shape.gauge_shapes:
1058                        gauge.gauge.Show(False)
1059                   
1060            self.active_wave = None
1061            self.timing_display = None
1062
1063            self.canvas.diagram.RemoveAllShapes()
1064            self.canvas.shapes = []
1065           
1066            tb = self.GetToolBar()
1067            tb.ToggleTool(wxID_TOOLBAR_TIMING_DISPLAY_TOOL, False)
1068            self.timing_view_state = False
1069            tb.SetToolShortHelp(wxID_TOOLBAR_TIMING_DISPLAY_TOOL, "Enable Timing Graphics")
1070            tb.ToggleTool(wxID_TOOLBAR_TIMING_TOOL, False)
1071            tb.SetToolShortHelp(wxID_TOOLBAR_TIMING_TOOL, "Enable Timing")
1072            #self.canvas.diagram = ogl.Diagram()
1073            #self.canvas.SetDiagram(self.canvas.diagram)
1074            #self.canvas.diagram.SetCanvas(self.canvas)
1075       
1076        self.canvas.Refresh()
1077
1078    def AddWaveformShape(self, waveform):
1079        tmpdisplay = ALFshapes.WaveformShapes(waveform, self.canvas)
1080        for comp in waveform.components:
1081            tmpdisplay.AddComponentShape(comp)
1082        tmpdisplay.ConnectComponents()
1083
1084        return tmpdisplay
1085
1086
1087    def updateWaveformData(self, data):
1088        for d in data:
1089            self.waveformData[d[0]] = d[1]
1090
1091        self.last_waveform_data_update = self.waveformData.copy()
1092
1093        for frame in self.tool_frames:
1094            if hasattr(frame, 'updateWaveformData'):
1095                frame.updateWaveformData(self.waveformData)
1096
1097    def removeToolFrame(self, frame):
1098        if frame not in self.tool_frames:
1099            return
1100        else:
1101            index = self.tool_frames.index(frame)
1102            del self.tool_frames[index]
1103           
1104    def OnClose(self, event):
1105        if self.nodeBooterProcess != None:
1106            dlg = wx.MessageDialog(self,
1107                                   "NodeBooter was started by ALF.\n" +
1108                                   "Would you like to terminate it?",
1109                                   "Confirm NodeBooter Termination", wx.YES | wx.NO | wx.ICON_QUESTION)
1110            result = dlg.ShowModal()
1111            if result == wx.ID_YES:
1112                print "Terminating nodeBooter"
1113                self.nodeBooterProcess.terminate()
1114        self.Destroy()
1115   
1116   
1117   
1118#----------------------------------------------------------------------
1119class MainWindow(ogl.ShapeCanvas):
1120    def __init__(self, parent, frame):
1121        ogl.ShapeCanvas.__init__(self, parent)
1122
1123        maxWidth  = 3000
1124        maxHeight = 1500
1125        self.SetScrollbars(20, 20, maxWidth/20, maxHeight/20)
1126
1127        self.frame = frame
1128        self.SetBackgroundColour("LIGHT BLUE") #wxWHITE)
1129        self.diagram = ogl.Diagram()
1130        self.SetDiagram(self.diagram)
1131        self.diagram.SetCanvas(self)
1132        self.shapes = []
1133
1134        dsBrush = wx.Brush("WHEAT", wx.SOLID)
1135       
1136    def updateDisplay(self, waveformdisplay):
1137        dc = wx.ClientDC(self)
1138        self.PrepareDC(dc)
1139        for compshape in waveformdisplay.shapes:
1140            self.AddShape(compshape)
1141            compshape.Show(True)
1142       
1143        self. diagram.Redraw(dc)
1144        self.Refresh()
1145                                                                       
1146    def OnDestroy(self, evt):
1147        # Do some cleanup
1148        for shape in self.diagram.GetShapeList():
1149            if shape.GetParent() == None:
1150                shape.SetCanvas(None)
1151                shape.Destroy()
1152        self.diagram.Destroyparent
1153       
1154    def setOSSIEProperty(self, sectionName, propertyName, propertyValue):
1155        configFile = os.getenv('HOME') + '/' + OSSIE_CONFIG_FILE
1156        configParser = ConfigParser.SafeConfigParser()
1157        #check to see if a config file already exists
1158        if os.path.exists(configFile):
1159            #if so, read in its properties so they don't get lost
1160            configParser.read(configFile)
1161        if not configParser.has_section(sectionName):
1162            configParser.add_section(sectionName)
1163        configParser.set(sectionName, propertyName, propertyValue)
1164        f = open(configFile, 'w')
1165        configParser.write(f)
1166        f.close()
1167           
1168    def getOSSIEProperty(self, sectionName, propertyName):
1169        configFile = os.getenv('HOME') + '/' + OSSIE_CONFIG_FILE
1170        if os.path.exists(configFile):
1171            configParser = ConfigParser.SafeConfigParser()
1172            configParser.read(configFile)
1173            if configParser.has_option(sectionName, propertyName):
1174                return configParser.get(sectionName, propertyName)
1175        return None
1176#----------------------------------------------------------------------
1177
1178def errorMsg(self,msg):
1179    dlg = wx.MessageDialog(self,msg,'Error', wx.OK | wx.ICON_INFORMATION)
1180    try:
1181        dlg.ShowModal()
1182    finally:
1183        dlg.Destroy()
1184    return
1185                               
1186
1187def main():
1188    app = alfApp(0)
1189    app.MainLoop()
1190
1191
1192# # If not profiling:
1193if __name__ == '__main__':
1194    main()
1195
1196
1197'''
1198# A script created by Drew Cormier for profiling
1199# code developed for his thesis
1200if __name__ == "__main__":
1201
1202    import profile
1203    import pstats
1204
1205    # bias the profile to remove profiling overhead
1206    # note that the number being passed to
1207    # bias varies based on what system I am using
1208    #
1209    # Aquire this number for my linux machine using
1210    # >>> p.calibrate(10000000)
1211    profile.bias = 1.6989519401052302e-05
1212
1213    profile.run("main()", "alf_profile_1")
1214
1215    my_stats = pstats.Stats("alf_profile_1")
1216
1217    my_stats.sort_stats('cumulative')
1218    my_stats.print_stats(10)
1219
1220    my_stats.sort_stats('time')
1221    my_stats.print_stats(10)
1222'''
1223
1224
1225
1226
1227
1228
1229
Note: See TracBrowser for help on using the browser.