PLCOpenEditor.py
changeset 1792 4d1de8b0183f
parent 1791 3216ed1ba1f7
child 1814 fc387c4fc1d4
equal deleted inserted replaced
1791:3216ed1ba1f7 1792:4d1de8b0183f
    24 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    24 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
    25 
    25 
    26 import wx
    26 import wx
    27 import os
    27 import os
    28 import sys
    28 import sys
    29 import platform
       
    30 import time
       
    31 import traceback
       
    32 import getopt
    29 import getopt
       
    30 
    33 import version
    31 import version
    34 import util.paths as paths
    32 import util.paths as paths
       
    33 import util.ExceptionHandler
    35 
    34 
    36 
    35 
    37 beremiz_dir = paths.AbsDir(__file__)
    36 beremiz_dir = paths.AbsDir(__file__)
    38 
    37 
    39 __version__ = "$Revision: 1.130 $"
       
    40 
    38 
    41 if __name__ == '__main__':
    39 if __name__ == '__main__':
    42     # Usage message displayed when help request or when error detected in
    40     # Usage message displayed when help request or when error detected in
    43     # command line
    41     # command line
    44     def usage():
    42     def usage():
    77     from util.misc import InstallLocalRessources
    75     from util.misc import InstallLocalRessources
    78     InstallLocalRessources(beremiz_dir)
    76     InstallLocalRessources(beremiz_dir)
    79 
    77 
    80     # these imports require wx.GetApp to return
    78     # these imports require wx.GetApp to return
    81     # a valid application instance
    79     # a valid application instance
    82     from docutil import *
    80 
    83     from IDEFrame import IDEFrame, AppendMenu
    81     from IDEFrame import IDEFrame, AppendMenu
    84     from IDEFrame import \
    82     from IDEFrame import \
    85         TITLE, \
    83         TITLE, \
    86         EDITORTOOLBAR, \
    84         EDITORTOOLBAR, \
    87         FILEMENU, \
    85         FILEMENU, \
   413             else:
   411             else:
   414                 self.ShowErrorMessage(_("\"%s\" is not a valid folder!") % os.path.dirname(filepath))
   412                 self.ShowErrorMessage(_("\"%s\" is not a valid folder!") % os.path.dirname(filepath))
   415             self._Refresh(TITLE, FILEMENU, PAGETITLES)
   413             self._Refresh(TITLE, FILEMENU, PAGETITLES)
   416         dialog.Destroy()
   414         dialog.Destroy()
   417 
   415 
   418 # -------------------------------------------------------------------------------
       
   419 #                               Exception Handler
       
   420 # -------------------------------------------------------------------------------
       
   421 
       
   422 
       
   423 Max_Traceback_List_Size = 20
       
   424 
       
   425 
       
   426 def Display_Exception_Dialog(e_type, e_value, e_tb):
       
   427     trcbck_lst = []
       
   428     for i, line in enumerate(traceback.extract_tb(e_tb)):
       
   429         trcbck = " " + str(i+1) + _(". ")
       
   430         if line[0].find(os.getcwd()) == -1:
       
   431             trcbck += _("file : ") + str(line[0]) + _(",   ")
       
   432         else:
       
   433             trcbck += _("file : ") + str(line[0][len(os.getcwd()):]) + _(",   ")
       
   434         trcbck += _("line : ") + str(line[1]) + _(",   ") + _("function : ") + str(line[2])
       
   435         trcbck_lst.append(trcbck)
       
   436 
       
   437     # Allow clicking....
       
   438     cap = wx.Window_GetCapture()
       
   439     if cap:
       
   440         cap.ReleaseMouse()
       
   441 
       
   442     dlg = wx.SingleChoiceDialog(
       
   443         None,
       
   444         _("""
       
   445 An unhandled exception (bug) occured. Bug report saved at :
       
   446 (%s)
       
   447 
       
   448 Please be kind enough to send this file to:
       
   449 beremiz-devel@lists.sourceforge.net
       
   450 
       
   451 You should now restart program.
       
   452 
       
   453 Traceback:
       
   454 """) % bug_report_path +
       
   455         repr(e_type) + " : " + repr(e_value),
       
   456         _("Error"),
       
   457         trcbck_lst)
       
   458     try:
       
   459         res = (dlg.ShowModal() == wx.ID_OK)
       
   460     finally:
       
   461         dlg.Destroy()
       
   462 
       
   463     return res
       
   464 
       
   465 
       
   466 def Display_Error_Dialog(e_value):
       
   467     message = wx.MessageDialog(None, str(e_value), _("Error"), wx.OK | wx.ICON_ERROR)
       
   468     message.ShowModal()
       
   469     message.Destroy()
       
   470 
       
   471 
       
   472 def get_last_traceback(tb):
       
   473     while tb.tb_next:
       
   474         tb = tb.tb_next
       
   475     return tb
       
   476 
       
   477 
       
   478 def format_namespace(d, indent='    '):
       
   479     return '\n'.join(['%s%s: %s' % (indent, k, repr(v)[:10000]) for k, v in d.iteritems()])
       
   480 
       
   481 
       
   482 ignored_exceptions = []  # a problem with a line in a module is only reported once per session
       
   483 
       
   484 
       
   485 def AddExceptHook(path, app_version='[No version]'):
       
   486 
       
   487     def handle_exception(e_type, e_value, e_traceback):
       
   488         traceback.print_exception(e_type, e_value, e_traceback)  # this is very helpful when there's an exception in the rest of this func
       
   489         last_tb = get_last_traceback(e_traceback)
       
   490         ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
       
   491         if str(e_value).startswith("!!!"):
       
   492             Display_Error_Dialog(e_value)
       
   493         elif ex not in ignored_exceptions:
       
   494             result = Display_Exception_Dialog(e_type, e_value, e_traceback)
       
   495             if result:
       
   496                 ignored_exceptions.append(ex)
       
   497                 info = {
       
   498                     'app-title': wx.GetApp().GetAppName(),
       
   499                     'app-version': app_version,
       
   500                     'wx-version': wx.VERSION_STRING,
       
   501                     'wx-platform': wx.Platform,
       
   502                     'python-version': platform.python_version(),
       
   503                     'platform': platform.platform(),
       
   504                     'e-type': e_type,
       
   505                     'e-value': e_value,
       
   506                     'date': time.ctime(),
       
   507                     'cwd': os.getcwd(),
       
   508                     }
       
   509                 if e_traceback:
       
   510                     info['traceback'] = ''.join(traceback.format_tb(e_traceback)) + '%s: %s' % (e_type, e_value)
       
   511                     last_tb = get_last_traceback(e_traceback)
       
   512                     exception_locals = last_tb.tb_frame.f_locals  # the locals at the level of the stack trace where the exception actually occurred
       
   513                     info['locals'] = format_namespace(exception_locals)
       
   514                     if 'self' in exception_locals:
       
   515                         info['self'] = format_namespace(exception_locals['self'].__dict__)
       
   516 
       
   517                 output = open(path+os.sep+"bug_report_"+time.strftime("%Y_%m_%d__%H-%M-%S")+".txt", 'w')
       
   518                 lst = info.keys()
       
   519                 lst.sort()
       
   520                 for a in lst:
       
   521                     output.write(a+":\n"+str(info[a])+"\n\n")
       
   522 
       
   523     # sys.excepthook = lambda *args: wx.CallAfter(handle_exception, *args)
       
   524     sys.excepthook = handle_exception
       
   525 
       
   526 
   416 
   527 if __name__ == '__main__':
   417 if __name__ == '__main__':
   528     if wx.VERSION < (3, 0, 0):
   418     if wx.VERSION < (3, 0, 0):
   529         wx.InitAllImageHandlers()
   419         wx.InitAllImageHandlers()
   530 
   420 
   531     # Install a exception handle for bug reports
   421     # Install a exception handle for bug reports
   532     AddExceptHook(os.getcwd(), version.app_version)
   422     util.ExceptionHandler.AddExceptHook(version.app_version)
   533 
   423 
   534     frame = PLCOpenEditor(None, fileOpen=fileOpen)
   424     frame = PLCOpenEditor(None, fileOpen=fileOpen)
   535 
   425 
   536     frame.Show()
   426     frame.Show()
   537     app.MainLoop()
   427     app.MainLoop()