]> rtime.felk.cvut.cz Git - CanFestival-3.git/blob - objdictgen/objdictedit.py
1b455c1231b77a11b16887a77ccf4ee20c31175d
[CanFestival-3.git] / objdictgen / objdictedit.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 #This file is part of CanFestival, a library implementing CanOpen Stack. 
5 #
6 #Copyright (C): Edouard TISSERANT, Francis DUPIN and Laurent BESSARD
7 #
8 #See COPYING file for copyrights details.
9 #
10 #This library is free software; you can redistribute it and/or
11 #modify it under the terms of the GNU Lesser General Public
12 #License as published by the Free Software Foundation; either
13 #version 2.1 of the License, or (at your option) any later version.
14 #
15 #This library is distributed in the hope that it will be useful,
16 #but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 #Lesser General Public License for more details.
19 #
20 #You should have received a copy of the GNU Lesser General Public
21 #License along with this library; if not, write to the Free Software
22 #Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24 import wx
25
26 from types import *
27 import os, re, platform, sys, time, traceback, getopt
28
29 __version__ = "$Revision: 1.30 $"
30
31 from node import OD_Subindex, OD_MultipleSubindexes, OD_IdenticalSubindexes, OD_IdenticalIndexes
32
33 from nodemanager import *
34 from subindextable import *
35 from commondialogs import *
36 from doc_index.DS301_index import *
37
38 try:
39     import wx.html
40
41     EVT_HTML_URL_CLICK = wx.NewId()
42
43     class HtmlWindowUrlClick(wx.PyEvent):
44         def __init__(self, linkinfo):
45             wx.PyEvent.__init__(self)
46             self.SetEventType(EVT_HTML_URL_CLICK)
47             self.linkinfo = (linkinfo.GetHref(), linkinfo.GetTarget())
48             
49     class UrlClickHtmlWindow(wx.html.HtmlWindow):
50         """ HTML window that generates and OnLinkClicked event.
51
52         Use this to avoid having to override HTMLWindow
53         """
54         def OnLinkClicked(self, linkinfo):
55             wx.PostEvent(self, HtmlWindowUrlClick(linkinfo))
56         
57         def Bind(self, event, handler, source=None, id=wx.ID_ANY, id2=wx.ID_ANY):
58             if event == HtmlWindowUrlClick:
59                 self.Connect(-1, -1, EVT_HTML_URL_CLICK, handler)
60             else:
61                 wx.html.HtmlWindow.Bind(event, handler, source=source, id=id, id2=id2)
62     
63 #-------------------------------------------------------------------------------
64 #                                Html Frame
65 #-------------------------------------------------------------------------------
66
67     [ID_HTMLFRAME, ID_HTMLFRAMEHTMLCONTENT] = [wx.NewId() for _init_ctrls in range(2)]
68
69     class HtmlFrame(wx.Frame):
70         def _init_ctrls(self, prnt):
71             wx.Frame.__init__(self, id=ID_HTMLFRAME, name='HtmlFrame',
72                   parent=prnt, pos=wx.Point(320, 231), size=wx.Size(853, 616),
73                   style=wx.DEFAULT_FRAME_STYLE, title='')
74             self.Bind(wx.EVT_CLOSE, self.OnCloseFrame)
75             
76             self.HtmlContent = UrlClickHtmlWindow(id=ID_HTMLFRAMEHTMLCONTENT,
77                   name='HtmlContent', parent=self, pos=wx.Point(0, 0),
78                   size=wx.Size(-1, -1), style=wx.html.HW_SCROLLBAR_AUTO|wx.html.HW_NO_SELECTION)
79             self.HtmlContent.Bind(HtmlWindowUrlClick, self.OnLinkClick)
80
81         def __init__(self, parent, opened):
82             self._init_ctrls(parent)
83             self.HtmlFrameOpened = opened
84         
85         def SetHtmlCode(self, htmlcode):
86             self.HtmlContent.SetPage(htmlcode)
87             
88         def SetHtmlPage(self, htmlpage):
89             self.HtmlContent.LoadPage(htmlpage)
90             
91         def OnCloseFrame(self, event):
92             self.HtmlFrameOpened.remove(self.GetTitle())
93             event.Skip()
94         
95         def OnLinkClick(self, event):
96             url = event.linkinfo[0]
97             try:
98                 import webbrowser
99             except ImportError:
100                 wx.MessageBox('Please point your browser at: %s' % url)
101             else:
102                 webbrowser.open(url)
103
104     Html_Window = True
105 except:
106     Html_Window = False
107
108 ScriptDirectory = os.path.split(__file__)[0]
109
110 [ID_OBJDICTEDIT, ID_OBJDICTEDITFILEOPENED, 
111  ID_OBJDICTEDITHELPBAR,
112 ] = [wx.NewId() for _init_ctrls in range(3)]
113
114 [ID_OBJDICTEDITADDMENUITEMS0, ID_OBJDICTEDITADDMENUITEMS1, 
115  ID_OBJDICTEDITADDMENUITEMS2, ID_OBJDICTEDITADDMENUITEMS3, 
116  ID_OBJDICTEDITADDMENUITEMS4, ID_OBJDICTEDITADDMENUITEMS5, 
117 ] = [wx.NewId() for _init_coll_AddMenu_Items in range(6)]
118
119 [ID_OBJDICTEDITFILEMENUITEMS0, ID_OBJDICTEDITFILEMENUITEMS1, 
120  ID_OBJDICTEDITFILEMENUITEMS2, ID_OBJDICTEDITFILEMENUITEMS4, 
121  ID_OBJDICTEDITFILEMENUITEMS5, ID_OBJDICTEDITFILEMENUITEMS6, 
122  ID_OBJDICTEDITFILEMENUITEMS7, ID_OBJDICTEDITFILEMENUITEMS8,
123  ID_OBJDICTEDITFILEMENUITEMS9,
124 ] = [wx.NewId() for _init_coll_FileMenu_Items in range(9)]
125
126 [ID_OBJDICTEDITEDITMENUITEMS0, ID_OBJDICTEDITEDITMENUITEMS1, 
127  ID_OBJDICTEDITEDITMENUITEMS2, ID_OBJDICTEDITEDITMENUITEMS4, 
128  ID_OBJDICTEDITEDITMENUITEMS6, ID_OBJDICTEDITEDITMENUITEMS7, 
129  ID_OBJDICTEDITEDITMENUITEMS8, 
130 ] = [wx.NewId() for _init_coll_EditMenu_Items in range(7)]
131
132 [ID_OBJDICTEDITHELPMENUITEMS0, ID_OBJDICTEDITHELPMENUITEMS1,
133  ID_OBJDICTEDITHELPMENUITEMS2,
134 ] = [wx.NewId() for _init_coll_HelpMenu_Items in range(3)]
135
136 class objdictedit(wx.Frame):
137     def _init_coll_menuBar1_Menus(self, parent):
138         parent.Append(menu=self.FileMenu, title='File')
139         parent.Append(menu=self.EditMenu, title='Edit')
140         parent.Append(menu=self.AddMenu, title='Add')
141         parent.Append(menu=self.HelpMenu, title='Help')
142
143     def _init_coll_EditMenu_Items(self, parent):
144         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS4,
145               kind=wx.ITEM_NORMAL, text='Refresh\tCTRL+R')
146         parent.AppendSeparator()
147         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS1,
148               kind=wx.ITEM_NORMAL, text='Undo\tCTRL+Z')
149         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS0,
150               kind=wx.ITEM_NORMAL, text='Redo\tCTRL+Y')
151         parent.AppendSeparator()
152         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS6,
153               kind=wx.ITEM_NORMAL, text='Node infos')
154         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS2,
155               kind=wx.ITEM_NORMAL, text='DS-301 Profile')
156         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS8,
157               kind=wx.ITEM_NORMAL, text='DS-302 Profile')
158         parent.Append(help='', id=ID_OBJDICTEDITEDITMENUITEMS7,
159               kind=wx.ITEM_NORMAL, text='Other Profile')
160         self.Bind(wx.EVT_MENU, self.OnUndoMenu,
161               id=ID_OBJDICTEDITEDITMENUITEMS1)
162         self.Bind(wx.EVT_MENU, self.OnRedoMenu,
163               id=ID_OBJDICTEDITEDITMENUITEMS0)
164         self.Bind(wx.EVT_MENU, self.OnCommunicationMenu,
165               id=ID_OBJDICTEDITEDITMENUITEMS2)
166         self.Bind(wx.EVT_MENU, self.OnRefreshMenu,
167               id=ID_OBJDICTEDITEDITMENUITEMS4)
168         self.Bind(wx.EVT_MENU, self.OnNodeInfosMenu,
169               id=ID_OBJDICTEDITEDITMENUITEMS6)
170         self.Bind(wx.EVT_MENU, self.OnEditProfileMenu,
171               id=ID_OBJDICTEDITEDITMENUITEMS7)
172         self.Bind(wx.EVT_MENU, self.OnOtherCommunicationMenu,
173               id=ID_OBJDICTEDITEDITMENUITEMS8)
174
175     def _init_coll_HelpMenu_Items(self, parent):
176         parent.Append(help='', id=ID_OBJDICTEDITHELPMENUITEMS0,
177               kind=wx.ITEM_NORMAL, text='DS-301 Standard\tF1')
178         self.Bind(wx.EVT_MENU, self.OnHelpDS301Menu,
179               id=ID_OBJDICTEDITHELPMENUITEMS0)
180         parent.Append(help='', id=ID_OBJDICTEDITHELPMENUITEMS1,
181               kind=wx.ITEM_NORMAL, text='CAN Festival Docs\tF2')
182         self.Bind(wx.EVT_MENU, self.OnHelpCANFestivalMenu,
183               id=ID_OBJDICTEDITHELPMENUITEMS1)
184         if Html_Window:
185             parent.Append(help='', id=ID_OBJDICTEDITHELPMENUITEMS2,
186                   kind=wx.ITEM_NORMAL, text='About')
187             self.Bind(wx.EVT_MENU, self.OnAboutMenu,
188                   id=ID_OBJDICTEDITHELPMENUITEMS2)
189
190     def _init_coll_FileMenu_Items(self, parent):
191         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS5,
192               kind=wx.ITEM_NORMAL, text='New\tCTRL+N')
193         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS0,
194               kind=wx.ITEM_NORMAL, text='Open\tCTRL+O')
195         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS1,
196               kind=wx.ITEM_NORMAL, text='Save\tCTRL+S')
197         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS6,
198               kind=wx.ITEM_NORMAL, text='Save As...\tALT+S')
199         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS2,
200               kind=wx.ITEM_NORMAL, text='Close\tCTRL+W')
201         parent.AppendSeparator()
202         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS7,
203               kind=wx.ITEM_NORMAL, text='Import EDS file')
204         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS9,
205               kind=wx.ITEM_NORMAL, text='Export to EDS file')
206         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS8,
207               kind=wx.ITEM_NORMAL, text='Build Dictionary\tCTRL+B')
208         parent.AppendSeparator()
209         parent.Append(help='', id=ID_OBJDICTEDITFILEMENUITEMS4,
210               kind=wx.ITEM_NORMAL, text='Exit')
211         self.Bind(wx.EVT_MENU, self.OnOpenMenu,
212               id=ID_OBJDICTEDITFILEMENUITEMS0)
213         self.Bind(wx.EVT_MENU, self.OnSaveMenu,
214               id=ID_OBJDICTEDITFILEMENUITEMS1)
215         self.Bind(wx.EVT_MENU, self.OnCloseMenu,
216               id=ID_OBJDICTEDITFILEMENUITEMS2)
217         self.Bind(wx.EVT_MENU, self.OnQuitMenu,
218               id=ID_OBJDICTEDITFILEMENUITEMS4)
219         self.Bind(wx.EVT_MENU, self.OnNewMenu,
220               id=ID_OBJDICTEDITFILEMENUITEMS5)
221         self.Bind(wx.EVT_MENU, self.OnSaveAsMenu,
222               id=ID_OBJDICTEDITFILEMENUITEMS6)
223         self.Bind(wx.EVT_MENU, self.OnImportEDSMenu,
224               id=ID_OBJDICTEDITFILEMENUITEMS7)
225         self.Bind(wx.EVT_MENU, self.OnExportCMenu,
226               id=ID_OBJDICTEDITFILEMENUITEMS8)
227         self.Bind(wx.EVT_MENU, self.OnExportEDSMenu,
228               id=ID_OBJDICTEDITFILEMENUITEMS9)
229
230     def _init_coll_AddMenu_Items(self, parent):
231         parent.Append(help='', id=ID_OBJDICTEDITADDMENUITEMS0,
232               kind=wx.ITEM_NORMAL, text='SDO Server')
233         parent.Append(help='', id=ID_OBJDICTEDITADDMENUITEMS1,
234               kind=wx.ITEM_NORMAL, text='SDO Client')
235         parent.Append(help='', id=ID_OBJDICTEDITADDMENUITEMS2,
236               kind=wx.ITEM_NORMAL, text='PDO Transmit')
237         parent.Append(help='', id=ID_OBJDICTEDITADDMENUITEMS3,
238               kind=wx.ITEM_NORMAL, text='PDO Receive')
239         parent.Append(help='', id=ID_OBJDICTEDITADDMENUITEMS4,
240               kind=wx.ITEM_NORMAL, text='Map Variable')
241         parent.Append(help='', id=ID_OBJDICTEDITADDMENUITEMS5,
242               kind=wx.ITEM_NORMAL, text='User Type')
243         self.Bind(wx.EVT_MENU, self.OnAddSDOServerMenu,
244               id=ID_OBJDICTEDITADDMENUITEMS0)
245         self.Bind(wx.EVT_MENU, self.OnAddSDOClientMenu,
246               id=ID_OBJDICTEDITADDMENUITEMS1)
247         self.Bind(wx.EVT_MENU, self.OnAddPDOTransmitMenu,
248               id=ID_OBJDICTEDITADDMENUITEMS2)
249         self.Bind(wx.EVT_MENU, self.OnAddPDOReceiveMenu,
250               id=ID_OBJDICTEDITADDMENUITEMS3)
251         self.Bind(wx.EVT_MENU, self.OnAddMapVariableMenu,
252               id=ID_OBJDICTEDITADDMENUITEMS4)
253         self.Bind(wx.EVT_MENU, self.OnAddUserTypeMenu,
254               id=ID_OBJDICTEDITADDMENUITEMS5)
255
256     def _init_coll_HelpBar_Fields(self, parent):
257         parent.SetFieldsCount(3)
258
259         parent.SetStatusText(number=0, text='')
260         parent.SetStatusText(number=1, text='')
261         parent.SetStatusText(number=2, text='')
262
263         parent.SetStatusWidths([100, 110, -1])
264
265     def _init_utils(self):
266         self.menuBar1 = wx.MenuBar()
267         self.menuBar1.SetEvtHandlerEnabled(True)
268
269         self.FileMenu = wx.Menu(title='')
270         self.EditMenu = wx.Menu(title='')
271         self.AddMenu = wx.Menu(title='')
272         self.HelpMenu = wx.Menu(title='')
273
274         self._init_coll_menuBar1_Menus(self.menuBar1)
275         self._init_coll_FileMenu_Items(self.FileMenu)
276         self._init_coll_EditMenu_Items(self.EditMenu)
277         self._init_coll_AddMenu_Items(self.AddMenu)
278         self._init_coll_HelpMenu_Items(self.HelpMenu)
279
280     def _init_ctrls(self, prnt):
281         wx.Frame.__init__(self, id=ID_OBJDICTEDIT, name='objdictedit',
282               parent=prnt, pos=wx.Point(149, 178), size=wx.Size(1000, 700),
283               style=wx.DEFAULT_FRAME_STYLE, title='Objdictedit')
284         self._init_utils()
285         self.SetClientSize(wx.Size(1000, 700))
286         self.SetMenuBar(self.menuBar1)
287         self.Bind(wx.EVT_CLOSE, self.OnCloseFrame)
288
289         self.FileOpened = wx.Notebook(id=ID_OBJDICTEDITFILEOPENED,
290               name='FileOpened', parent=self, pos=wx.Point(0, 0),
291               size=wx.Size(0, 0), style=0)
292         self.FileOpened.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED,
293               self.OnFileSelectedChanged, id=ID_OBJDICTEDITFILEOPENED)
294
295         self.HelpBar = wx.StatusBar(id=ID_OBJDICTEDITHELPBAR, name='HelpBar',
296               parent=self, style=wx.ST_SIZEGRIP)
297         self._init_coll_HelpBar_Fields(self.HelpBar)
298         self.SetStatusBar(self.HelpBar)
299
300     def __init__(self, parent, filesOpen = []):
301         self._init_ctrls(parent)
302         self.HtmlFrameOpened = []
303         self.ModeSolo = True
304         
305         self.Manager = NodeManager()
306         for filepath in filesOpen:
307             result = self.Manager.OpenFileInCurrent(filepath)
308             if type(result) == IntType:
309                 new_editingpanel = EditingPanel(self, self.Manager)
310                 new_editingpanel.SetIndex(result)
311                 self.FileOpened.AddPage(new_editingpanel, "")
312             window = self.FileOpened.GetPage(0)
313             if window:
314                 self.Manager.ChangeCurrentNode(window.GetIndex())
315                 self.FileOpened.SetSelection(0)
316         if self.Manager.CurrentDS302Defined():
317             self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS8, True)
318         else:
319             self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS8, False)
320         self.RefreshEditMenu()
321         self.RefreshBufferState()
322         self.RefreshProfileMenu()
323         self.RefreshTitle()
324         self.RefreshMainMenu()
325
326     def GetNoteBook(self):
327         return self.FileOpened
328
329     def OnAddSDOServerMenu(self, event):
330         self.Manager.AddSDOServerToCurrent()
331         self.RefreshBufferState()
332         self.RefreshCurrentIndexList()
333         event.Skip()
334     
335     def OnAddSDOClientMenu(self, event):
336         self.Manager.AddSDOClientToCurrent()
337         self.RefreshBufferState()
338         self.RefreshCurrentIndexList()
339         event.Skip()
340
341     def OnAddPDOTransmitMenu(self, event):
342         self.Manager.AddPDOTransmitToCurrent()
343         self.RefreshBufferState()
344         self.RefreshCurrentIndexList()
345         event.Skip()
346
347     def OnAddPDOReceiveMenu(self, event):
348         self.Manager.AddPDOReceiveToCurrent()
349         self.RefreshBufferState()
350         self.RefreshCurrentIndexList()
351         event.Skip()
352
353     def OnAddMapVariableMenu(self, event):
354         self.AddMapVariable()
355         event.Skip()
356
357     def OnAddUserTypeMenu(self, event):
358         self.AddUserType()
359         event.Skip()
360
361     def OnFileSelectedChanged(self, event):
362         selected = event.GetSelection()
363         # At init selected = -1
364         if selected >= 0:
365             window = self.FileOpened.GetPage(selected)
366             if window:
367                 self.Manager.ChangeCurrentNode(window.GetIndex())
368                 self.RefreshBufferState()
369                 self.RefreshStatusBar()
370                 self.RefreshProfileMenu()
371         event.Skip()
372
373     def OnHelpDS301Menu(self, event):
374         find_index = False
375         selected = self.FileOpened.GetSelection()
376         if selected >= 0:
377             window = self.FileOpened.GetPage(selected)
378             result = window.GetSelection()
379             if result:
380                 find_index = True
381                 index, subIndex = result
382                 result = OpenPDFDocIndex(index, ScriptDirectory)
383                 if type(result) == StringType:
384                     message = wx.MessageDialog(self, result, "ERROR", wx.OK|wx.ICON_ERROR)
385                     message.ShowModal()
386                     message.Destroy()
387         if not find_index:
388             result = OpenPDFDocIndex(None, ScriptDirectory)
389             if type(result) == StringType:
390                 message = wx.MessageDialog(self, result, "ERROR", wx.OK|wx.ICON_ERROR)
391                 message.ShowModal()
392                 message.Destroy()
393         event.Skip()
394         
395     def OnHelpCANFestivalMenu(self, event):
396         #self.OpenHtmlFrame("CAN Festival Reference", os.path.join(ScriptDirectory, "doc/canfestival.html"), wx.Size(1000, 600))
397         os.system("xpdf -remote CANFESTIVAL %s %d &"%(os.path.join(ScriptDirectory, "doc/manual_en.pdf"),16))
398         event.Skip()
399
400     def OnAboutMenu(self, event):
401         self.OpenHtmlFrame("About CAN Festival", os.path.join(ScriptDirectory, "doc/about.html"), wx.Size(500, 450))
402         event.Skip()
403
404     def OpenHtmlFrame(self, title, file, size):
405         if title not in self.HtmlFrameOpened:
406             self.HtmlFrameOpened.append(title)
407             window = HtmlFrame(self, self.HtmlFrameOpened)
408             window.SetTitle(title)
409             window.SetHtmlPage(file)
410             window.SetClientSize(size)
411             window.Show()
412
413     def OnQuitMenu(self, event):
414         self.Close()
415         event.Skip()
416     
417     def OnCloseFrame(self, event):
418         if self.Manager.OneFileHasChanged():
419             dialog = wx.MessageDialog(self, "There are changes, do you want to save?",  "Close Application", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
420             answer = dialog.ShowModal()
421             dialog.Destroy()
422             if answer == wx.ID_YES:
423                 self.Manager.ChangeCurrentNode(0)
424                 for i in xrange(self.FileOpened.GetPageCount()):
425                     window = self.FileOpened.GetPage(i)
426                     self.Manager.ChangeCurrentNode(window.GetIndex())
427                     if self.Manager.CurrentIsSaved():
428                         self.Manager.CloseCurrent()
429                     else:
430                         self.Save()
431                         self.Manager.CloseCurrent(True)
432                 event.Skip()
433             elif answer == wx.ID_NO:
434                 for i in xrange(self.FileOpened.GetPageCount()):
435                     self.Manager.CloseCurrent(True)
436                 wx.CallAfter(self.Close)
437                 event.Skip()
438         else:
439             event.Skip()
440
441 #-------------------------------------------------------------------------------
442 #                             Refresh Functions
443 #-------------------------------------------------------------------------------
444
445     def RefreshTitle(self):
446         if self.FileOpened.GetPageCount() > 0:
447             self.SetTitle("Objdictedit - %s"%self.Manager.GetCurrentFilename())
448         else:
449             self.SetTitle("Objdictedit")
450
451     def OnRefreshMenu(self, event):
452         self.RefreshCurrentIndexList()
453         event.Skip()
454
455     def RefreshCurrentIndexList(self):
456         selected = self.FileOpened.GetSelection()
457         window = self.FileOpened.GetPage(selected)
458         window.RefreshIndexList()
459
460     def RefreshStatusBar(self):
461         if self.HelpBar:
462             selected = self.FileOpened.GetSelection()
463             if selected >= 0:
464                 window = self.FileOpened.GetPage(selected)
465                 selection = window.GetSelection()
466                 if selection:
467                     index, subIndex = selection
468                     if self.Manager.IsCurrentEntry(index):
469                         self.HelpBar.SetStatusText("Index: 0x%04X"%index, 0)
470                         self.HelpBar.SetStatusText("Subindex: 0x%02X"%subIndex, 1)
471                         entryinfos = self.Manager.GetEntryInfos(index)
472                         name = entryinfos["name"]
473                         category = "Optional"
474                         if entryinfos["need"]:
475                             category = "Mandatory"
476                         struct = "VAR"
477                         number = ""
478                         if entryinfos["struct"] & OD_IdenticalIndexes:
479                             number = " possibly defined %d times"%entryinfos["nbmax"]
480                         if entryinfos["struct"] & OD_IdenticalSubindexes:
481                             struct = "REC"
482                         elif entryinfos["struct"] & OD_MultipleSubindexes:
483                             struct = "ARRAY"
484                         text = "%s: %s entry of struct %s%s."%(name,category,struct,number)
485                         self.HelpBar.SetStatusText(text, 2)
486                     else:
487                         for i in xrange(3):
488                             self.HelpBar.SetStatusText("", i)
489                 else:
490                     for i in xrange(3):
491                         self.HelpBar.SetStatusText("", i)
492
493     def RefreshMainMenu(self):
494         if self.FileMenu:
495             if self.FileOpened.GetPageCount() > 0:
496                 self.menuBar1.EnableTop(1, True)
497                 self.menuBar1.EnableTop(2, True)
498                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS1, True)
499                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS2, True)
500                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS6, True)
501                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS8, True)
502                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS9, True)
503             else:
504                 self.menuBar1.EnableTop(1, False)
505                 self.menuBar1.EnableTop(2, False)
506                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS1, False)
507                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS2, False)
508                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS6, False)
509                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS8, False)
510                 self.FileMenu.Enable(ID_OBJDICTEDITFILEMENUITEMS9, False)
511
512     def RefreshEditMenu(self):
513         if self.FileMenu:
514             if self.FileOpened.GetPageCount() > 0:
515                 undo, redo = self.Manager.GetCurrentBufferState()
516                 self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS1, undo)
517                 self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS0, redo)
518             else:
519                 self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS1, False)
520                 self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS0, False)
521
522     def RefreshProfileMenu(self):
523         if self.EditMenu:
524             profile = self.Manager.GetCurrentProfileName()
525             edititem = self.EditMenu.FindItemById(ID_OBJDICTEDITEDITMENUITEMS7)
526             if edititem:
527                 length = self.AddMenu.GetMenuItemCount()
528                 for i in xrange(length-6):
529                     additem = self.AddMenu.FindItemByPosition(6)
530                     self.AddMenu.Delete(additem.GetId())
531                 if profile not in ("None", "DS-301"):
532                     edititem.SetText("%s Profile"%profile)
533                     edititem.Enable(True)
534                     self.AddMenu.AppendSeparator()
535                     for text, indexes in self.Manager.GetCurrentSpecificMenu():
536                         new_id = wx.NewId()
537                         self.AddMenu.Append(help='', id=new_id, kind=wx.ITEM_NORMAL, text=text)
538                         self.Bind(wx.EVT_MENU, self.GetProfileCallBack(text), id=new_id)
539                 else:
540                     edititem.SetText("Other Profile")
541                     edititem.Enable(False)
542         
543
544 #-------------------------------------------------------------------------------
545 #                            Buffer Functions
546 #-------------------------------------------------------------------------------
547
548     def RefreshBufferState(self):
549         fileopened = self.Manager.GetAllFilenames()
550         for idx, filename in enumerate(fileopened):
551             self.FileOpened.SetPageText(idx, filename)
552         self.RefreshEditMenu()
553         self.RefreshTitle()
554
555     def OnUndoMenu(self, event):
556         self.Manager.LoadCurrentPrevious()
557         self.RefreshCurrentIndexList()
558         self.RefreshBufferState()
559         event.Skip()
560
561     def OnRedoMenu(self, event):
562         self.Manager.LoadCurrentNext()
563         self.RefreshCurrentIndexList()
564         self.RefreshBufferState()
565         event.Skip()
566
567
568 #-------------------------------------------------------------------------------
569 #                         Load and Save Funtions
570 #-------------------------------------------------------------------------------
571
572     def OnNewMenu(self, event):
573         self.FilePath = ""
574         dialog = CreateNodeDialog(self)
575         if dialog.ShowModal() == wx.ID_OK:
576             name, id, nodetype, description = dialog.GetValues()
577             profile, filepath = dialog.GetProfile()
578             NMT = dialog.GetNMTManagement()
579             options = dialog.GetOptions()
580             result = self.Manager.CreateNewNode(name, id, nodetype, description, profile, filepath, NMT, options)
581             if type(result) == IntType:
582                 new_editingpanel = EditingPanel(self, self.Manager)
583                 new_editingpanel.SetIndex(result)
584                 self.FileOpened.AddPage(new_editingpanel, "")
585                 self.FileOpened.SetSelection(self.FileOpened.GetPageCount() - 1)
586                 self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS8, False)
587                 if "DS302" in options:
588                     self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS8, True)
589                 self.RefreshBufferState()
590                 self.RefreshProfileMenu()
591                 self.RefreshMainMenu()
592             else:
593                 message = wx.MessageDialog(self, result, "ERROR", wx.OK|wx.ICON_ERROR)
594                 message.ShowModal()
595                 message.Destroy()
596         event.Skip()
597
598     def OnOpenMenu(self, event):
599         filepath = self.Manager.GetCurrentFilePath()
600         if filepath != "":
601             directory = os.path.dirname(filepath)
602         else:
603             directory = os.getcwd()
604         dialog = wx.FileDialog(self, "Choose a file", directory, "",  "OD files (*.od)|*.od|All files|*.*", wx.OPEN|wx.CHANGE_DIR)
605         if dialog.ShowModal() == wx.ID_OK:
606             filepath = dialog.GetPath()
607             if os.path.isfile(filepath):
608                 result = self.Manager.OpenFileInCurrent(filepath)
609                 if type(result) == IntType:
610                     new_editingpanel = EditingPanel(self, self.Manager)
611                     new_editingpanel.SetIndex(result)
612                     self.FileOpened.AddPage(new_editingpanel, "")
613                     self.FileOpened.SetSelection(self.FileOpened.GetPageCount() - 1)
614                     if self.Manager.CurrentDS302Defined(): 
615                         self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS8, True)
616                     else:
617                         self.EditMenu.Enable(ID_OBJDICTEDITEDITMENUITEMS8, False)
618                     self.RefreshEditMenu()
619                     self.RefreshBufferState()
620                     self.RefreshProfileMenu()
621                     self.RefreshMainMenu()
622                 else:
623                     message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
624                     message.ShowModal()
625                     message.Destroy()
626         dialog.Destroy()
627         event.Skip()
628
629     def OnSaveMenu(self, event):
630         self.Save()
631         event.Skip()
632     
633     def OnSaveAsMenu(self, event):
634         self.SaveAs()
635         event.Skip()
636         
637     def Save(self):
638         result = self.Manager.SaveCurrentInFile()
639         if not result:
640             self.SaveAs()
641         elif type(result) != StringType:
642             self.RefreshBufferState()
643         else:
644             message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
645             message.ShowModal()
646             message.Destroy()
647
648     def SaveAs(self):
649         filepath = self.Manager.GetCurrentFilePath()
650         if filepath != "":
651             directory, filename = os.path.split(filepath)
652         else:
653             directory, filename = os.getcwd(), "%s.od"%self.Manager.GetCurrentNodeInfos()[0]
654         dialog = wx.FileDialog(self, "Choose a file", directory, filename,  "OD files (*.od)|*.od|All files|*.*", wx.SAVE|wx.OVERWRITE_PROMPT|wx.CHANGE_DIR)
655         if dialog.ShowModal() == wx.ID_OK:
656             filepath = dialog.GetPath()
657             if os.path.isdir(os.path.dirname(filepath)):
658                 result = self.Manager.SaveCurrentInFile(filepath)
659                 if type(result) != StringType:
660                     self.RefreshBufferState()
661                 else:
662                     message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
663                     message.ShowModal()
664                     message.Destroy()
665             else:
666                 message = wx.MessageDialog(self, "%s is not a valid folder!"%os.path.dirname(filepath), "Error", wx.OK|wx.ICON_ERROR)
667                 message.ShowModal()
668                 message.Destroy()
669         dialog.Destroy()
670
671     def OnCloseMenu(self, event):
672         answer = wx.ID_YES
673         result = self.Manager.CloseCurrent()
674         if not result:
675             dialog = wx.MessageDialog(self, "There are changes, do you want to save?",  "Close File", wx.YES_NO|wx.CANCEL|wx.ICON_QUESTION)
676             answer = dialog.ShowModal()
677             dialog.Destroy()
678             if answer == wx.ID_YES:
679                 self.OnSaveMenu(event)
680                 if self.Manager.CurrentIsSaved():
681                     self.Manager.CloseCurrent()
682             elif answer == wx.ID_NO:
683                 self.Manager.CloseCurrent(True)
684         if self.FileOpened.GetPageCount() > self.Manager.GetBufferNumber():
685             current = self.FileOpened.GetSelection()
686             self.FileOpened.DeletePage(current)
687             if self.FileOpened.GetPageCount() > 0:
688                 self.FileOpened.SetSelection(min(current, self.FileOpened.GetPageCount() - 1))
689             self.RefreshBufferState()
690             self.RefreshMainMenu()
691         event.Skip()
692         
693
694 #-------------------------------------------------------------------------------
695 #                         Import and Export Functions
696 #-------------------------------------------------------------------------------
697
698     def OnImportEDSMenu(self, event):
699         dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), "",  "EDS files (*.eds)|*.eds|All files|*.*", wx.OPEN|wx.CHANGE_DIR)
700         if dialog.ShowModal() == wx.ID_OK:
701             filepath = dialog.GetPath()
702             if os.path.isfile(filepath):
703                 result = self.Manager.ImportCurrentFromEDSFile(filepath)
704                 if type(result) == IntType:
705                     new_editingpanel = EditingPanel(self, self.Manager)
706                     new_editingpanel.SetIndex(result)
707                     self.FileOpened.AddPage(new_editingpanel, "")
708                     self.FileOpened.SetSelection(self.FileOpened.GetPageCount() - 1)
709                     self.RefreshBufferState()
710                     self.RefreshCurrentIndexList()
711                     self.RefreshProfileMenu()
712                     self.RefreshMainMenu()
713                     message = wx.MessageDialog(self, "Import successful", "Information", wx.OK|wx.ICON_INFORMATION)
714                     message.ShowModal()
715                     message.Destroy()
716                 else:
717                     message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
718                     message.ShowModal()
719                     message.Destroy()
720             else:
721                 message = wx.MessageDialog(self, "\"%s\" is not a valid file!"%filepath, "Error", wx.OK|wx.ICON_ERROR)
722                 message.ShowModal()
723                 message.Destroy()
724         dialog.Destroy()
725         event.Skip()
726
727
728     def OnExportEDSMenu(self, event):
729         dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), self.Manager.GetCurrentNodeInfos()[0], "EDS files (*.eds)|*.eds|All files|*.*", wx.SAVE|wx.OVERWRITE_PROMPT|wx.CHANGE_DIR)
730         if dialog.ShowModal() == wx.ID_OK:
731             filepath = dialog.GetPath()
732             if os.path.isdir(os.path.dirname(filepath)):
733                 path, extend = os.path.splitext(filepath)
734                 if extend in ("", "."):
735                     filepath = path + ".eds"
736                 result = self.Manager.ExportCurrentToEDSFile(filepath)
737                 if not result:
738                     message = wx.MessageDialog(self, "Export successful", "Information", wx.OK|wx.ICON_INFORMATION)
739                     message.ShowModal()
740                     message.Destroy()
741                 else:
742                     message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
743                     message.ShowModal()
744                     message.Destroy()
745             else:
746                 message = wx.MessageDialog(self, "\"%s\" is not a valid folder!"%os.path.dirname(filepath), "Error", wx.OK|wx.ICON_ERROR)
747                 message.ShowModal()
748                 message.Destroy()
749         dialog.Destroy()
750         event.Skip()
751
752     def OnExportCMenu(self, event):
753         dialog = wx.FileDialog(self, "Choose a file", os.getcwd(), self.Manager.GetCurrentNodeInfos()[0],  "CANFestival C files (*.c)|*.c|All files|*.*", wx.SAVE|wx.OVERWRITE_PROMPT|wx.CHANGE_DIR)
754         if dialog.ShowModal() == wx.ID_OK:
755             filepath = dialog.GetPath()
756             if os.path.isdir(os.path.dirname(filepath)):
757                 path, extend = os.path.splitext(filepath)
758                 if extend in ("", "."):
759                     filepath = path + ".c"
760                 result = self.Manager.ExportCurrentToCFile(filepath)
761                 if not result:
762                     message = wx.MessageDialog(self, "Export successful", "Information", wx.OK|wx.ICON_INFORMATION)
763                     message.ShowModal()
764                     message.Destroy()
765                 else:
766                     message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
767                     message.ShowModal()
768                     message.Destroy()
769             else:
770                 message = wx.MessageDialog(self, "\"%s\" is not a valid folder!"%os.path.dirname(filepath), "Error", wx.OK|wx.ICON_ERROR)
771                 message.ShowModal()
772                 message.Destroy()
773         dialog.Destroy()
774         event.Skip()
775
776 #-------------------------------------------------------------------------------
777 #                          Editing Profiles functions
778 #-------------------------------------------------------------------------------
779
780     def OnCommunicationMenu(self, event):
781         dictionary,current = self.Manager.GetCurrentCommunicationLists()
782         self.EditProfile("Edit DS-301 Profile", dictionary, current)
783         event.Skip()
784     
785     def OnOtherCommunicationMenu(self, event):
786         dictionary,current = self.Manager.GetCurrentDS302Lists()
787         self.EditProfile("Edit DS-301 Profile", dictionary, current)
788         event.Skip()
789     
790     def OnEditProfileMenu(self, event):
791         title = "Edit %s Profile"%self.Manager.GetCurrentProfileName()
792         dictionary,current = self.Manager.GetCurrentProfileLists()
793         self.EditProfile(title, dictionary, current)
794         event.Skip()
795     
796     def EditProfile(self, title, dictionary, current):
797         dialog = CommunicationDialog(self)
798         dialog.SetTitle(title)
799         dialog.SetIndexDictionary(dictionary)
800         dialog.SetCurrentList(current)
801         dialog.RefreshLists()
802         if dialog.ShowModal() == wx.ID_OK:
803             new_profile = dialog.GetCurrentList()
804             addinglist = []
805             removinglist = []
806             for index in new_profile:
807                 if index not in current:
808                     addinglist.append(index)
809             for index in current:
810                 if index not in new_profile:
811                     removinglist.append(index)
812             self.Manager.ManageEntriesOfCurrent(addinglist, removinglist)
813             self.Manager.BufferCurrentNode()
814             self.RefreshBufferState()
815             self.RefreshCurrentIndexList()
816         dialog.Destroy()
817
818     def GetProfileCallBack(self, text):
819         def ProfileCallBack(event):
820             self.Manager.AddSpecificEntryToCurrent(text)
821             self.RefreshBufferState()
822             self.RefreshCurrentIndexList()
823             event.Skip()
824         return ProfileCallBack
825
826 #-------------------------------------------------------------------------------
827 #                         Edit Node informations function
828 #-------------------------------------------------------------------------------
829
830     def OnNodeInfosMenu(self, event):
831         dialog = NodeInfosDialog(self)
832         name, id, type, description = self.Manager.GetCurrentNodeInfos()
833         dialog.SetValues(name, id, type, description)
834         if dialog.ShowModal() == wx.ID_OK:
835             name, id, type, description = dialog.GetValues()
836             self.Manager.SetCurrentNodeInfos(name, id, type, description)
837             self.RefreshBufferState()
838             self.RefreshProfileMenu()
839             selected = self.FileOpened.GetSelection()
840             if selected >= 0:
841                 window = self.FileOpened.GetPage(selected)
842                 window.RefreshTable()
843         event.Skip()
844
845
846 #-------------------------------------------------------------------------------
847 #                           Add User Types and Variables
848 #-------------------------------------------------------------------------------
849         
850     def AddMapVariable(self):
851         index = self.Manager.GetCurrentNextMapIndex()
852         if index:
853             dialog = MapVariableDialog(self)
854             dialog.SetIndex(index)
855             if dialog.ShowModal() == wx.ID_OK:
856                 index, name, struct, number = dialog.GetValues()
857                 result = self.Manager.AddMapVariableToCurrent(index, name, struct, number)
858                 if type(result) != StringType:
859                     self.RefreshBufferState()
860                     self.RefreshCurrentIndexList()
861                 else:
862                     message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
863                     message.ShowModal()
864                     message.Destroy()
865             dialog.Destroy()
866         else:
867             message = wx.MessageDialog(self, result, "No map variable index left!", wx.OK|wx.ICON_ERROR)
868             message.ShowModal()
869             message.Destroy()
870         
871     def AddUserType(self):
872         dialog = UserTypeDialog(self)
873         dialog.SetTypeList(self.Manager.GetCustomisableTypes())
874         if dialog.ShowModal() == wx.ID_OK:
875             type, min, max, length = dialog.GetValues()
876             result = self.Manager.AddUserTypeToCurrent(type, min, max, length)
877             if not result:
878                 self.RefreshBufferState()
879                 self.RefreshCurrentIndexList()
880             else:
881                 message = wx.MessageDialog(self, result, "Error", wx.OK|wx.ICON_ERROR)
882                 message.ShowModal()
883                 message.Destroy()
884         dialog.Destroy()
885     
886
887 #-------------------------------------------------------------------------------
888 #                               Exception Handler
889 #-------------------------------------------------------------------------------
890
891 Max_Traceback_List_Size = 20
892
893 def Display_Exception_Dialog(e_type,e_value,e_tb):
894     trcbck_lst = []
895     for i,line in enumerate(traceback.extract_tb(e_tb)):
896         trcbck = " " + str(i+1) + ". "
897         if line[0].find(os.getcwd()) == -1:
898             trcbck += "file : " + str(line[0]) + ",   "
899         else:
900             trcbck += "file : " + str(line[0][len(os.getcwd()):]) + ",   "
901         trcbck += "line : " + str(line[1]) + ",   " + "function : " + str(line[2])
902         trcbck_lst.append(trcbck)
903         
904     # Allow clicking....
905     cap = wx.Window_GetCapture()
906     if cap:
907         cap.ReleaseMouse()
908
909     dlg = wx.SingleChoiceDialog(None, 
910         """
911 An error happens.
912
913 Click on OK for saving an error report.
914
915 Please contact LOLITech at:
916 +33 (0)3 29 52 95 67
917 bugs_objdictedit@lolitech.fr
918
919
920 Error:
921 """ +
922         str(e_type) + " : " + str(e_value), 
923         "Error",
924         trcbck_lst)
925     try:
926         res = (dlg.ShowModal() == wx.ID_OK)
927     finally:
928         dlg.Destroy()
929
930     return res
931
932 def Display_Error_Dialog(e_value):
933     message = wx.MessageDialog(None, str(e_value), "Error", wx.OK|wx.ICON_ERROR)
934     message.ShowModal()
935     message.Destroy()
936
937 def get_last_traceback(tb):
938     while tb.tb_next:
939         tb = tb.tb_next
940     return tb
941
942
943 def format_namespace(d, indent='    '):
944     return '\n'.join(['%s%s: %s' % (indent, k, repr(v)[:10000]) for k, v in d.iteritems()])
945
946
947 ignored_exceptions = [] # a problem with a line in a module is only reported once per session
948
949 def AddExceptHook(path, app_version='[No version]'):#, ignored_exceptions=[]):
950     
951     def handle_exception(e_type, e_value, e_traceback):
952         traceback.print_exception(e_type, e_value, e_traceback) # this is very helpful when there's an exception in the rest of this func
953         last_tb = get_last_traceback(e_traceback)
954         ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
955         if str(e_value).startswith("!!!"):
956             Display_Error_Dialog(e_value)
957         elif ex not in ignored_exceptions:
958             ignored_exceptions.append(ex)
959             result = Display_Exception_Dialog(e_type,e_value,e_traceback)
960             if result:
961                 info = {
962                     'app-title' : wx.GetApp().GetAppName(), # app_title
963                     'app-version' : app_version,
964                     'wx-version' : wx.VERSION_STRING,
965                     'wx-platform' : wx.Platform,
966                     'python-version' : platform.python_version(), #sys.version.split()[0],
967                     'platform' : platform.platform(),
968                     'e-type' : e_type,
969                     'e-value' : e_value,
970                     'date' : time.ctime(),
971                     'cwd' : os.getcwd(),
972                     }
973                 if e_traceback:
974                     info['traceback'] = ''.join(traceback.format_tb(e_traceback)) + '%s: %s' % (e_type, e_value)
975                     last_tb = get_last_traceback(e_traceback)
976                     exception_locals = last_tb.tb_frame.f_locals # the locals at the level of the stack trace where the exception actually occurred
977                     info['locals'] = format_namespace(exception_locals)
978                     if 'self' in exception_locals:
979                         info['self'] = format_namespace(exception_locals['self'].__dict__)
980                 
981                 output = open(path+os.sep+"bug_report_"+info['date'].replace(':','-').replace(' ','_')+".txt",'w')
982                 lst = info.keys()
983                 lst.sort()
984                 for a in lst:
985                     output.write(a+":\n"+str(info[a])+"\n\n")
986
987     #sys.excepthook = lambda *args: wx.CallAfter(handle_exception, *args)
988     sys.excepthook = handle_exception
989
990 if __name__ == '__main__':
991     def usage():
992         print "\nUsage of objdictedit.py :"
993         print "\n   %s [Filepath, ...]\n"%sys.argv[0]
994
995     try:
996         opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
997     except getopt.GetoptError:
998         # print help information and exit:
999         usage()
1000         sys.exit(2)
1001
1002     for o, a in opts:
1003         if o in ("-h", "--help"):
1004             usage()
1005             sys.exit()
1006     
1007     app = wx.PySimpleApp()
1008     wx.InitAllImageHandlers()
1009     
1010     # Install a exception handle for bug reports
1011     AddExceptHook(os.getcwd(),__version__)
1012     
1013     frame = objdictedit(None, args)
1014
1015     frame.Show()
1016     app.MainLoop()