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