forked from capocchi/DEVSimPy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevsimpy.py
More file actions
2592 lines (2071 loc) · 89.9 KB
/
devsimpy.py
File metadata and controls
2592 lines (2071 loc) · 89.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# devsimpy.py --- DEVSimPy - The Python DEVS GUI modeling and simulation software
# --------------------------------
# Copyright (c) 2021
# L. CAPOCCHI (capocchi@univ-corse.fr)
# SPE Lab - SISU Group - University of Corsica
# --------------------------------
# Version 4.0 last modified: 05/15/20
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#
# GENERAL NOTES AND REMARKS:
#
# strong depends: wxPython, PyPubSub (3.3.0)
# light depends: NumPy for spectrum analysis, mathplotlib for graph display
# remarks: lib tree is build by the TreeLitLib class.
# Moreover, __init__.py file is required for the build (see GetSubDomain method).
# in order to make a lib:
# 1/ make a MyLib rep with Message.py, DomainBehavior.py and DomaineStrucutre.py
# 2/ __all_ = [] in __init__.py file must use return
# 3/ python file that is not in __all__ is not imported
# 4/ the constructor of all class must have a default value of the parameters
# 5/ __str__ method must be implemented for .py in order to have a correct
# name in the GUI (otherwise AM is displayed)
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
#
# GLOBAL VARIABLES AND FUNCTIONS
#
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
import datetime
import copy
import os
import sys
import time
import locale
import re
import gettext
import builtins
import platform
import threading
import subprocess
import pickle
import builtins
import glob
import pstats
from configparser import ConfigParser
from tempfile import gettempdir
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
__authors__ = "Laurent Capocchi <capocchi_l@univ-corse.fr>, SISU project group <santucci_j@univ-corse.fr>"
__date__ = str(datetime.datetime.now())
__version__ = '4.0'
__docformat__ = 'epytext'
__min_wx_version__ = '4.0'
ABS_HOME_PATH = os.path.abspath(os.path.dirname(sys.argv[0]))
################################################################
### Loading wx python library
################################################################
### ini file exist ?
parser = ConfigParser()
parser.read(os.path.join(os.path.expanduser("~"),'devsimpy.ini'))
section, option = ('wxversion', 'to_load')
ini_exist = parser.has_option(section, option)
import wx
### check if an upgrade of wxpython is possible from pip !
sys.stdout.write("Importing wxPython %s%s for python %s on %s (%s) platform...\n"%(wx.version(), " from devsimpy.ini" if ini_exist else '', platform.python_version(), platform.system(), platform.version()))
import gettext
_ = gettext.gettext
try:
import wx.aui as aui
except:
import wx.lib.agw.aui as aui
import wx.py as py
import wx.lib.dialogs
import wx.html
import wx.lib.mixins.inspection as wit
try:
from wx.lib.agw import advancedsplash
AdvancedSplash = advancedsplash.AdvancedSplash
old = False
except ImportError:
AdvancedSplash = wx.SplashScreen
old = True
# to send event
try:
from pubsub import pub
except Exception:
sys.stdout.write('Last version for Python2 is PyPubSub 3.3.0 \n pip install PyPubSub==3.3.0')
sys.exit()
if wx.VERSION_STRING >= '4.0':
import wx.adv
wx.FutureCall = wx.CallLater
wx.SAVE = wx.FD_SAVE
wx.OPEN = wx.FD_OPEN
wx.DEFAULT_STYLE = wx.FD_DEFAULT_STYLE
wx.MULTIPLE = wx.FD_MULTIPLE
wx.CHANGE_DIR = wx.FD_CHANGE_DIR
wx.OVERWRITE_PROMPT = wx.FD_OVERWRITE_PROMPT
wx.AboutDialogInfo = wx.adv.AboutDialogInfo
wx.AboutBox = wx.adv.AboutBox
### specific built-in variables. (don't modify the default value. If you want to change it, go to the PreferencesGUI from devsimpy interface.)
builtin_dict = {'SPLASH_PNG': os.path.join(ABS_HOME_PATH, 'splash', 'splash.png'), # abslolute path
'DEVSIMPY_PNG': 'iconDEVSimPy.png', # png file for devsimpy icon
'HOME_PATH': ABS_HOME_PATH,
'ICON_PATH': os.path.join(ABS_HOME_PATH, 'icons'),
'ICON_PATH_16_16': os.path.join(ABS_HOME_PATH, 'icons', '16x16'),
'SIMULATION_SUCCESS_SOUND_PATH': os.path.join(ABS_HOME_PATH,'sounds', 'Simulation-Success.wav'),
'SIMULATION_ERROR_SOUND_PATH': os.path.join(ABS_HOME_PATH,'sounds', 'Simulation-Error.wav'),
'DOMAIN_PATH': os.path.join(ABS_HOME_PATH, 'Domain'), # path of local lib directory
'NB_OPENED_FILE': 5, # number of recent files
'NB_HISTORY_UNDO': 5, # number of undo
'OUT_DIR': 'out', # name of local output directory (composed by all .dat, .txt files)
'PLUGINS_PATH': os.path.join(ABS_HOME_PATH, 'plugins'), # path of plug-ins directory
'FONT_SIZE': 12, # Block font size
'LOCAL_EDITOR': True, # for the use of local editor
'EXTERNAL_EDITOR_NAME': "", # the name of the external code editor (only if LOCAL_EDITOR is False)
'LOG_FILE': os.devnull, # log file (null by default)
'DEFAULT_SIM_STRATEGY': 'bag-based', #choose the default simulation strategy for PyDEVS
'PYDEVS_SIM_STRATEGY_DICT' : {'original':'SimStrategy1', 'bag-based':'SimStrategy2', 'direct-coupling':'SimStrategy3'}, # list of available simulation strategy for PyDEVS package
'PYPDEVS_SIM_STRATEGY_DICT' : {'classic':'SimStrategy4', 'parallel':'SimStrategy5'}, # list of available simulation strategy for PyPDEVS package
'PYPDEVS_221_SIM_STRATEGY_DICT' : {'classic':'SimStrategy4', 'parallel':'SimStrategy5'}, # list of available simulation strategy for PyPDEVS package
'HELP_PATH' : os.path.join('doc', 'html'), # path of help directory
'NTL' : False, # No Time Limit for the simulation
'DYNAMIC_STRUCTURE' : False, # Dynamic Structure for local PyPDEVS simulation
'REAL_TIME': False, ### PyPDEVS threaded real time simulation
'VERBOSE':False,
'TRANSPARENCY' : True, # Transparancy for DetachedFrame
'NOTIFICATION': True,
'DEFAULT_PLOT_DYN_FREQ' : 100, # frequence of dynamic plot of QuickScope (to avoid overhead),
'DEFAULT_DEVS_DIRNAME':'PyDEVS', # default DEVS Kernel directory
'DEVS_DIR_PATH_DICT':{'PyDEVS':os.path.join(ABS_HOME_PATH,'DEVSKernel','PyDEVS'),
'PyPDEVS_221':os.path.join(ABS_HOME_PATH,'DEVSKernel','PyPDEVS','pypdevs221' ,'src'),
'PyPDEVS':os.path.join(ABS_HOME_PATH,'DEVSKernel','PyPDEVS','old')},
'GUI_FLAG':True
}
### Check if the pypdevs241 directory is empty (not --recursive option when the devsimpy git has been cloned)
path = os.path.join(ABS_HOME_PATH,'DEVSKernel','PyPDEVS','pypdevs241')
if os.path.exists(path) and not len(os.listdir(path)) == 0:
builtin_dict['PYPDEVS_241_SIM_STRATEGY_DICT'] = {'classic':'SimStrategy4', 'parallel':'SimStrategy5'}
builtin_dict['DEVS_DIR_PATH_DICT'].update({'PyPDEVS_241':os.path.join(path ,'src','pypdevs')})
else:
sys.stdout.write("PyPDEVS Kernel in version 2.4.1 is not loaded.\nPlease install it in the directory %s using git (http://msdl.uantwerpen.be/git/yentl/PythonPDEVS.git)\n"%path)
### here berfore the __main__ function
### warning, some module (like SimulationGUI) initialise GUI_FLAG macro before (import block below)
#builtin_dict['GUI_FLAG'] = False
# Sets the homepath variable to the directory where your application is located (sys.argv[0]).
builtins.__dict__.update(builtin_dict)
### Deprecation warnings with Python 3.8
wx._core.WindowIDRef.__index__ = wx._core.WindowIDRef.__int__
### import Container much faster loading than from Container import ... for os windows only
import Container
import Menu
import ReloadModule
from ImportLibrary import ImportLibrary
from Reporter import ExceptionHook
from PreferencesGUI import PreferencesGUI
from PluginManager import PluginManager
from Utilities import GetUserConfigDir, install, install_and_import, updatePiPPackages, updateFromGitRepo, updateFromGitArchive, NotificationMessage
from Decorators import redirectStdout, BuzyCursorNotification, ProgressNotification, cond_decorator
from DetachedFrame import DetachedFrame
from LibraryTree import LibraryTree
from LibPanel import LibPanel
from PropPanel import PropPanel
from ControlNotebook import ControlNotebook
from DiagramNotebook import DiagramNotebook
from Editor import GetEditor
from YAMLExportGUI import YAMLExportGUI
from wxPyMail import SendMailWx
from XMLModule import getDiagramFromXMLSES
### only for wx 2.9 (bug)
### http://comments.gmane.org/gmane.comp.python.wxpython/98744
wx.Log.SetLogLevel(0)
#-------------------------------------------------------------------
def getIcon(path):
""" Return icon from image path.
"""
icon = wx.EmptyIcon() if wx.VERSION_STRING < '4.0' else wx.Icon()
bmp = wx.Bitmap(path)
bmp.SetMask(wx.Mask(bmp, wx.WHITE))
icon.CopyFromBitmap(bmp)
return icon
#-------------------------------------------------------------------
def DefineScreenSize(percentscreen = None, size = None):
""" Returns a tuple to define the size of the window
percentscreen = float
"""
if not size and not percentscreen:
percentscreen = 0.8
if size:
l, h = size
elif percentscreen:
x1, x2, l, h = wx.Display().GetClientArea()
l, h = percentscreen * l, percentscreen * h
return round(l), round(h)
# -------------------------------------------------------------------
class MainApplication(wx.Frame):
""" DEVSimPy main application.
"""
def __init__(self, parent, id, title):
""" Constructor.
"""
## Create Config file -------------------------------------------------------
self.cfg = self.GetConfig()
self.SetConfig(self.cfg)
## Set i18n locales --------------------------------------------------------
self.Seti18n()
wx.Frame.__init__(self, parent, wx.NewIdRef(), title, style = wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
self.window = None
self.otherWin = None
self.replace = False
self.stdioWin = None
# icon setting
self.icon = getIcon(os.path.join(ICON_PATH, DEVSIMPY_PNG))
self.SetIcon(self.icon)
# tell FrameManager to manage this frame
self._mgr = aui.AuiManager()
self._mgr.SetManagedWindow(self)
# Prevent TreeCtrl from displaying all items after destruction when True
self.dying = False
# if 0:
# # This is another way to set Accelerators, in addition to
# # using the '\t<key>' syntax in the menu items.
# aTable = wx.AcceleratorTable([(wx.ACCEL_ALT, ord('X'), exitID), (wx.ACCEL_CTRL, ord('H'), helpID),(wx.ACCEL_CTRL, ord('F'), findID),(wx.ACCEL_NORMAL, WXK_F3, findnextID)])
# self.SetAcceleratorTable(aTable)
# for spash screen
pub.sendMessage('object.added', message=_('Loading the libraries tree...\n'))
### for open home path
self.home = None
# NoteBook
self.nb1 = ControlNotebook(self, wx.NewIdRef(), style = wx.CLIP_CHILDREN)
self.tree = self.nb1.GetTree()
pub.sendMessage('object.added', message=_('Loading the search tab on libraries tree...\n'))
self.searchTree = self.nb1.GetSearchTree()
self._mgr.AddPane(self.nb1, aui.AuiPaneInfo().Name("nb1").Hide().Caption("Control").
FloatingSize(wx.Size(280, 400)).CloseButton(True).MaximizeButton(True))
#------------------------------------------------------------------------------------------
# Create a Notebook 2
self.nb2 = DiagramNotebook(self, wx.NewIdRef(), style = wx.CLIP_CHILDREN)
self.nb2.AddEditPage(_("Diagram%d"%Container.ShapeCanvas.ID))
self._mgr.AddPane(self.nb2, aui.AuiPaneInfo().Name("nb2").CenterPane().Hide())
# Simulation panel
self.panel3 = wx.Panel(self.nb1, wx.NewIdRef(), style = wx.WANTS_CHARS)
self.panel3.SetBackgroundColour(wx.NullColour)
self.panel3.Hide()
#status bar avant simulation :-)
self.MakeStatusBar()
# Shell panel
self.panel4 = wx.Panel(self, wx.NewIdRef(), style=wx.WANTS_CHARS)
sizer4 = wx.BoxSizer(wx.VERTICAL)
sizer4.Add(py.crust.Crust(self.panel4, intro=_("Welcome to DEVSimPy: The GUI for Python DEVS Simulator")), 1, wx.EXPAND)
self.panel4.SetSizer(sizer4)
self.panel4.SetAutoLayout(True)
self._mgr.AddPane(self.panel4, aui.AuiPaneInfo().Name("shell").Hide().Caption("Shell").
FloatingSize(wx.Size(280, 400)).CloseButton(True).MaximizeButton(True))
### Editor is panel
self.editor = GetEditor(self, -1, file_type='block')
self._mgr.AddPane(self.editor, aui.AuiPaneInfo().Name("editor").Hide().Caption(_("Editor")).
FloatingSize(wx.Size(280, 400)).CloseButton(True).MaximizeButton(True))
self._mgr.GetPane("nb1").Show().Left().Layer(0).Row(0).Position(0).BestSize(wx.Size(280,-1)).MinSize(wx.Size(250,-1))
self._mgr.GetPane("nb2").Show().Center().Layer(0).Row(1).Position(0)
self._mgr.GetPane("shell").Bottom().Layer(0).Row(0).Position(0).BestSize(wx.Size(-1,100)).MinSize(wx.Size(-1,120))
self._mgr.GetPane("editor").Right().Layer(0).Row(0).Position(0).BestSize(wx.Size(280,-1)).MinSize(wx.Size(250,-1))
# "commit" all changes made to FrameManager (warning always before the MakeMenu)
self._mgr.Update()
self.MakeMenu()
self.MakeToolBar()
self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnDragInit, id = self.tree.GetId())
#self.Bind(wx.EVT_TREE_END_DRAG, self.OnDragEnd, id = self.tree.GetId())
self.Bind(wx.EVT_TREE_BEGIN_DRAG, self.OnDragInit, id = self.searchTree.GetId())
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
sys.stdout.write("DEVSimPy is ready!\n")
### load last size and position if exist
self.SetSize(DefineScreenSize() if not self.last_size else self.last_size)
if self.last_position:
self.SetPosition(self.last_position)
else:
self.Centre(wx.BOTH)
self.Show()
def GetVersion(self):
return __version__
def GetMGR(self):
return self._mgr
def GetConfig(self):
""" Reads the config file for the application if it exists and return a configfile object for use later.
"""
return wx.FileConfig(localFilename = os.path.join(GetUserConfigDir(),'.devsimpy'))
def WriteDefaultConfigFile(self, cfg):
""" Write config file.
"""
### for spash screen
pub.sendMessage('object.added', message=_('Writing .devsimpy settings file...\n'))
sys.stdout.write("Writing default .devsimpy settings file on %s directory..."%GetUserConfigDir())
self.exportPathsList = [] # export path list
self.openFileList = ['']*NB_OPENED_FILE # number of last opened files
self.language = 'fr' if 'fr_FR' in locale.getdefaultlocale() else 'en' # default language
self.perspectives = {} # perpsective is void
self.last_position = None
self.last_size = None
### verison of the main (fo compatibility of DEVSimPy)
cfg.Write('version', str(__version__))
### list des chemins des librairies à importer
cfg.Write('exportPathsList', str([]))
### list de l'unique domain par defaut: Basic
cfg.Write('ChargedDomainList', str([]))
### list des 5 derniers fichier ouvert
cfg.Write('openFileList', str(eval("self.openFileList")))
cfg.Write('language', "'%s'"%str(eval("self.language")))
cfg.Write('active_plugins', str("[]"))
cfg.Write('perspectives', str(eval("self.perspectives")))
cfg.Write('builtin_dict', str(eval("builtins.__dict__")))
cfg.Write('last_position', str(eval("self.last_position")))
cfg.Write('last_size', str(eval("self.last_size")))
sys.stdout.write("OK! \n")
def SetConfig(self, cfg):
""" Set all config entry like language, external importpath, recent files...
"""
self.cfg = cfg
### if .devsimpy config file already exist, load it
if self.cfg.Exists('version'):
### rewrite old configuration file
rewrite = float(self.cfg.Read("version")) != float(self.GetVersion())
if not rewrite:
### for spash screen
pub.sendMessage('object.added', message=_('Loading .devsimpy settings file...\n'))
sys.stdout.write("Loading DEVSimPy %s settings file from %s.devsimpy\n"%(self.GetVersion(), GetUserConfigDir()+os.sep))
### load external import path
self.exportPathsList = [path for path in eval(self.cfg.Read("exportPathsList")) if os.path.isdir(path)]
### append external path to the sys module to futur import
sys.path.extend(self.exportPathsList)
### load recent files list
self.openFileList = eval(self.cfg.Read("openFileList"))
### update chargedDomainList
chargedDomainList = [path for path in eval(self.cfg.Read('ChargedDomainList')) if path.startswith('http') or os.path.isdir(path)]
self.cfg.DeleteEntry('ChargedDomainList')
self.cfg.Write('ChargedDomainList', str(eval('chargedDomainList')))
### load language
self.language = eval(self.cfg.Read("language"))
### load perspective profile
self.perspectives = eval(self.cfg.Read("perspectives"))
### load last position and size
try:
self.last_position = eval(self.cfg.Read("last_position"))
self.last_size = eval(self.cfg.Read("last_size"))
except:
self.last_position = None
self.last_size = None
else:
### check if the screen size has not changed (dual screen)
if self.last_position:
l_saved,h_saved=self.last_position
### if the position saved is superior of the screen
l,h=DefineScreenSize()
if l_saved>l or h_saved>h:
self.last_position = None
self.last_size = None
### restore the builtin dict
try:
D = eval(self.cfg.Read("builtin_dict"))
except SyntaxError:
wx.MessageBox('Error trying to read the builtin dictionary from config file. So, we load the default builtin',
'Configuration',
wx.OK | wx.ICON_INFORMATION)
#sys.stdout.write('Error trying to read the builtin dictionary from config file. So, we load the default builtin \n')
D = builtin_dict
else:
### try to start without error when .devsimpy need update (new version installed)
if not os.path.isdir(D['HOME_PATH']):
wx.MessageBox('.devsimpy file appears to be not liked with the DEVSimPy code source. Please, delete this configuration from %s file and restart DEVSimPy. \n'%(GetUserConfigDir()),
'Configuration',
wx.OK | wx.ICON_INFORMATION)
#sys.stdout.write('.devsimpy file appear to be not liked with the DEVSimPy source. Please, delete this configuration from %s file and restart DEVSimPy. \n'%(GetUserConfigDir()))
D['HOME_PATH'] = ABS_HOME_PATH
### if pypdevs_241 is detected, it is added in the builtin in order to be able to select him from the simulation Preference panel
if builtin_dict['DEVS_DIR_PATH_DICT'] != D['DEVS_DIR_PATH_DICT']:
D['DEVS_DIR_PATH_DICT'].update(builtin_dict['DEVS_DIR_PATH_DICT'])
try:
### recompile DomainInterface if DEFAULT_DEVS_DIRNAME != PyDEVS
recompile = D['DEFAULT_DEVS_DIRNAME'] != builtins.__dict__['DEFAULT_DEVS_DIRNAME']
except KeyError:
recompile = False
### test if the DEVSimPy source directory has been moved
### if icon path exists, then we can update builtin from cfg
if os.path.exists(D['ICON_PATH']):
builtins.__dict__.update(D)
### recompile DomainInterface
if recompile:
ReloadModule.recompile("DomainInterface.DomainBehavior")
ReloadModule.recompile("DomainInterface.DomainStructure")
ReloadModule.recompile("DomainInterface.MasterModel")
### icon path is wrong (generally .devsimpy is wrong because DEVSimPy directory has been moved)
### .devsimpy must be rewrite
else:
sys.stdout.write("It seems that DEVSimPy source directory has been moved.\n")
self.WriteDefaultConfigFile(self.cfg)
### load any plugins from the list
### here because it needs to PLUGINS_PATH macro defined in D
for plugin in eval(self.cfg.Read("active_plugins")):
PluginManager.load_plugins(plugin)
PluginManager.enable_plugin(plugin)
else:
wx.MessageBox('.devsimpy file appear to be a very old version and should be updated....\nWe rewrite a new blank version.',
'Configuration',
wx.OK | wx.ICON_INFORMATION)
self.WriteDefaultConfigFile(self.cfg)
### create a new defaut .devsimpy config file
else:
self.WriteDefaultConfigFile(self.cfg)
###sys.stdout.write("Loading DEVSimPy...\n")
def Seti18n(self):
""" Set local setting.
"""
# for spash screen
pub.sendMessage('object.added', message=_('Loading locale configuration...\n'))
localedir = os.path.join(HOME_PATH, "locale")
langid = wx.LANGUAGE_FRENCH if self.language == 'fr' else wx.LANGUAGE_ENGLISH # use OS default; or use LANGUAGE_FRENCH, etc.
domain = "DEVSimPy" # the translation file is messages.mo
# Set locale for wxWidgets
self.locale = wx.Locale()
self.locale.Init(langid)
self.locale.AddCatalogLookupPathPrefix(localedir)
self.locale.AddCatalog(domain)
# language config from .devsimpy file
if self.language in ('en','fr'):
try:
locale.setlocale(locale.LC_ALL, self.language)
except:
sys.stdout.write(_('new local (since wx 4.1.0) setting not applied'))
translation = gettext.translation(domain, localedir, languages=[self.language])
else:
try:
locale.setlocale(locale.LC_ALL, '')
except:
sys.stdout.write(_('new local (since wx 4.1.0) setting not applied'))
#installing os language by default
translation = gettext.translation(domain, localedir, [self.locale.GetCanonicalName()], fallback = True)
translation.install()
def MakeStatusBar(self):
""" Make status bar.
"""
# for spash screen
pub.sendMessage('object.added', message=_('Making status bar...\n'))
self.statusbar = self.CreateStatusBar(1, wx.ST_SIZEGRIP if wx.VERSION_STRING < '4.0' else wx.STB_SIZEGRIP)
self.statusbar.SetFieldsCount(3)
self.statusbar.SetStatusWidths([-2, -5, -1])
def MakeMenu(self):
""" Make main menu.
"""
# for spash screen
pub.sendMessage('object.added', message=_('Making Menu ...\n'))
self.menuBar = Menu.MainMenuBar(self)
self.SetMenuBar(self.menuBar)
### commented before Phoenix transition
### bind menu that require update on open and close event (forced to implement the binding here !)
for menu,title in [c for c in self.menuBar.GetMenus() if re.search("(File|Fichier|Options)", c[-1]) != None]:
self.Bind(wx.EVT_MENU_OPEN, self.menuBar.OnOpenMenu)
#self.Bind(wx.EVT_MENU_CLOSE, self.menuBar.OnCloseMenu)
def MakeToolBar(self):
""" Make main tools bar.
"""
# for spash screen
pub.sendMessage('object.added', message=_('Making tools bar ...\n'))
tb = wx.ToolBar(self, wx.NewIdRef(), name='tb', style=wx.TB_HORIZONTAL | wx.NO_BORDER)
tb.SetToolBitmapSize((16,16))
self.toggle_list = [wx.NewIdRef(), wx.NewIdRef(), wx.NewIdRef(), wx.NewIdRef(), wx.NewIdRef(), wx.NewIdRef()]
currentPage = self.nb2.GetCurrentPage()
### Tools List - IDs come from Menu.py file
if wx.VERSION_STRING < '4.0':
self.tools = [ tb.AddTool(wx.ID_NEW, wx.Bitmap(os.path.join(ICON_PATH,'new.png')), shortHelpString=_('New diagram (Ctrl+N)'),longHelpString=_('Create a new diagram in tab')),
tb.AddTool(wx.ID_OPEN, wx.Bitmap(os.path.join(ICON_PATH,'open.png')), shortHelpString=_('Open File (Ctrl+O)'), longHelpString=_('Open an existing diagram')),
tb.AddTool(wx.ID_PREVIEW_PRINT, wx.Bitmap(os.path.join(ICON_PATH,'print-preview.png')), shortHelpString=_('Print Preview (Ctrl+P)'), longHelpString=_('Print preview of current diagram')),
tb.AddTool(wx.ID_SAVE, wx.Bitmap(os.path.join(ICON_PATH,'save.png')), shortHelpString=_('Save File (Ctrl+S)'), longHelpString=_('Save the current diagram'), clientData=currentPage),
tb.AddTool(wx.ID_SAVEAS, wx.Bitmap(os.path.join(ICON_PATH,'save_as.png')), shortHelpString=_('Save file as'), longHelpString=_('Save the diagram with an another name'), clientData=currentPage),
tb.AddTool(wx.ID_UNDO, wx.Bitmap(os.path.join(ICON_PATH,'undo.png')),shortHelpString= _('Undo'), longHelpString=_('Click to go upward, hold to see history'), clientData=currentPage),
tb.AddTool(wx.ID_REDO, wx.Bitmap(os.path.join(ICON_PATH,'redo.png')), shortHelpString=_('Redo'), longHelpString=_('Click to go forward, hold to see history'), clientData=currentPage),
tb.AddTool(Menu.ID_ZOOMIN_DIAGRAM, wx.Bitmap(os.path.join(ICON_PATH,'zoom+.png')), shortHelpString=_('Zoom'), longHelpString=_('Zoom +'), clientData=currentPage),
tb.AddTool(Menu.ID_ZOOMOUT_DIAGRAM, wx.Bitmap(os.path.join(ICON_PATH,'zoom-.png')), shortHelpString=_('UnZoom'), longHelpString=_('Zoom -'), clientData=currentPage),
tb.AddTool(Menu.ID_UNZOOM_DIAGRAM, wx.Bitmap(os.path.join(ICON_PATH,'no_zoom.png')), shortHelpString=_('AnnuleZoom'), longHelpString=_('Normal size'), clientData=currentPage),
tb.AddTool(Menu.ID_PRIORITY_DIAGRAM, wx.Bitmap(os.path.join(ICON_PATH,'priority.png')), shortHelpString=_('Priority (F3)'),longHelpString= _('Define model activation priority')),
tb.AddTool(Menu.ID_CHECK_DIAGRAM, wx.Bitmap(os.path.join(ICON_PATH,'check_master.png')), shortHelpString=_('Debugger (F4)'),longHelpString= _('Check devs models')),
tb.AddTool(Menu.ID_PLUGINS_SHAPE, wx.Bitmap(os.path.join(ICON_PATH,'plugins.png')), shortHelpString=_('Plugins'), longHelpString=_('Plugins Manager')),
tb.AddTool(Menu.ID_SIM_DIAGRAM, wx.Bitmap(os.path.join(ICON_PATH,'simulation.png')), shortHelpString=_('Simulation (F5)'), longHelpString=_('Simulate the diagram')),
tb.AddTool(self.toggle_list[0], wx.Bitmap(os.path.join(ICON_PATH,'direct_connector.png')),shortHelpString= _('Direct'),longHelpString=_('Direct connector'), isToggle=True),
tb.AddTool(self.toggle_list[1], wx.Bitmap(os.path.join(ICON_PATH,'square_connector.png')), shortHelpString=_('Square'), longHelpString=_('Square connector'), isToggle=True),
tb.AddTool(self.toggle_list[2], wx.Bitmap(os.path.join(ICON_PATH,'linear_connector.png')), shortHelpString=_('Linear'), longHelpString=_('Linear connector'), isToggle=True)
]
else:
self.tools = [ tb.AddTool(wx.ID_NEW, "",wx.Bitmap(os.path.join(ICON_PATH,'new.png')), shortHelp=_('New diagram (Ctrl+N)')),
tb.AddTool(wx.ID_OPEN, "",wx.Bitmap(os.path.join(ICON_PATH,'open.png')), shortHelp=_('Open File (Ctrl+O)')),
tb.AddTool(wx.ID_PREVIEW_PRINT, "",wx.Bitmap(os.path.join(ICON_PATH,'print-preview.png')), shortHelp=_('Print Preview (Ctrl+P)')),
tb.AddTool(wx.ID_SAVE, "",wx.Bitmap(os.path.join(ICON_PATH,'save.png')), wx.NullBitmap, shortHelp=_('Save File (Ctrl+S)'), longHelp=_('Save the current diagram'), clientData=currentPage),
tb.AddTool(wx.ID_SAVEAS, "",wx.Bitmap(os.path.join(ICON_PATH,'save_as.png')), wx.NullBitmap, shortHelp=_('Save file as'), longHelp=_('Save the diagram with an another name'), clientData=currentPage),
tb.AddTool(wx.ID_UNDO, "",wx.Bitmap(os.path.join(ICON_PATH,'undo.png')), wx.NullBitmap, shortHelp= _('Undo'), longHelp=_('Click to glongHelpString=o back, hold to see history'), clientData=currentPage),
tb.AddTool(wx.ID_REDO, "",wx.Bitmap(os.path.join(ICON_PATH,'redo.png')), wx.NullBitmap, shortHelp=_('Redo'), longHelp=_('Click to go forward, hold to see history'), clientData=currentPage),
tb.AddTool(Menu.ID_ZOOMIN_DIAGRAM, "",wx.Bitmap(os.path.join(ICON_PATH,'zoom+.png')), wx.NullBitmap, shortHelp=_('Zoom'), longHelp=_('Zoom +'), clientData=currentPage),
tb.AddTool(Menu.ID_ZOOMOUT_DIAGRAM, "",wx.Bitmap(os.path.join(ICON_PATH,'zoom-.png')), wx.NullBitmap, shortHelp=_('UnZoom'), longHelp=_('Zoom -'), clientData=currentPage),
tb.AddTool(Menu.ID_UNZOOM_DIAGRAM, "",wx.Bitmap(os.path.join(ICON_PATH,'no_zoom.png')), wx.NullBitmap, shortHelp=_('AnnuleZoom'), longHelp=_('Normal size'), clientData=currentPage),
tb.AddTool(Menu.ID_PRIORITY_DIAGRAM, "",wx.Bitmap(os.path.join(ICON_PATH,'priority.png')), shortHelp=_('Priority (F3)')),
tb.AddTool(Menu.ID_CHECK_DIAGRAM, "",wx.Bitmap(os.path.join(ICON_PATH,'check_master.png')), shortHelp=_('Debugger (F4)')),
tb.AddTool(Menu.ID_PLUGINS_SHAPE, "", wx.Bitmap(os.path.join(ICON_PATH,'plugins.png')), shortHelp=_('Plugins Manager')),
tb.AddTool(Menu.ID_SIM_DIAGRAM, "",wx.Bitmap(os.path.join(ICON_PATH,'simulation.png')), shortHelp=_('Simulation (F5)')),
tb.AddTool(self.toggle_list[0], "",wx.Bitmap(os.path.join(ICON_PATH,'direct_connector.png')),shortHelp= _('Direct'), kind=wx.ITEM_CHECK),
tb.AddTool(self.toggle_list[1], "",wx.Bitmap(os.path.join(ICON_PATH,'square_connector.png')), shortHelp=_('Square'), kind = wx.ITEM_CHECK),
tb.AddTool(self.toggle_list[2], "",wx.Bitmap(os.path.join(ICON_PATH,'linear_connector.png')), shortHelp=_('Linear'), kind = wx.ITEM_CHECK)
]
##################################################################### Abstraction hierarchy
diagram = currentPage.GetDiagram()
level = currentPage.GetCurrentLevel()
level_label = wx.StaticText(tb, -1, _("Level "))
self.spin = wx.SpinCtrl(tb, self.toggle_list[3], str(level), pos=(55, 90), size=(50, -1), min=0, max=20)
tb.AddControl(level_label)
tb.AddControl(self.spin)
### add button to define downward and upward rules
ID_UPWARD = self.toggle_list[4]
ID_DOWNWARD = self.toggle_list[5]
if wx.VERSION_STRING < '4.0':
self.tools.append(tb.AddTool(ID_DOWNWARD, wx.Bitmap(os.path.join(ICON_PATH,'downward.png')), shortHelpString=_('Downward rules'), longHelpString=_('Define Downward atomic model')))
self.tools.append(tb.AddTool(ID_UPWARD, wx.Bitmap(os.path.join(ICON_PATH,'upward.png')), shortHelpString=_('Upward rules'), longHelpString=_('Define Upward atomic model')))
else:
self.tools.append(tb.AddTool(ID_DOWNWARD, "", wx.Bitmap(os.path.join(ICON_PATH,'downward.png')), shortHelp=_('Downward rules')))
self.tools.append(tb.AddTool(ID_UPWARD, "", wx.Bitmap(os.path.join(ICON_PATH,'upward.png')), shortHelp=_('Upward rules')))
tb.EnableTool(ID_DOWNWARD, False)
tb.EnableTool(ID_UPWARD, False)
##############################################################################################
for i in (3,8,12,17,21):
tb.InsertSeparator(i)
### undo and redo button desabled
tb.EnableTool(wx.ID_UNDO, False)
tb.EnableTool(wx.ID_REDO, False)
tb.EnableTool(Menu.ID_PRIORITY_DIAGRAM, not 'PyPDEVS' in builtins.__dict__['DEFAULT_DEVS_DIRNAME'])
### default direct connector toogled
tb.ToggleTool(self.toggle_list[0], 1)
### Binding
self.Bind(wx.EVT_TOOL, self.OnNew, self.tools[0])
self.Bind(wx.EVT_TOOL, self.OnOpenFile, self.tools[1])
self.Bind(wx.EVT_TOOL, self.OnPrintPreview, self.tools[2])
self.Bind(wx.EVT_TOOL, self.OnSaveFile, self.tools[3])
self.Bind(wx.EVT_TOOL, self.OnSaveAsFile, self.tools[4])
self.Bind(wx.EVT_TOOL, self.OnUndo, self.tools[5])
self.Bind(wx.EVT_TOOL, self.OnRedo, self.tools[6])
self.Bind(wx.EVT_TOOL, self.OnZoom, self.tools[7])
self.Bind(wx.EVT_TOOL, self.OnUnZoom, self.tools[8])
self.Bind(wx.EVT_TOOL, self.AnnuleZoom, self.tools[9])
self.Bind(wx.EVT_TOOL, self.OnPriorityGUI, self.tools[10])
self.Bind(wx.EVT_TOOL, self.OnCheck, self.tools[11])
self.Bind(wx.EVT_TOOL, self.OnPlugins, self.tools[12])
self.Bind(wx.EVT_TOOL, self.OnSimulation, self.tools[13])
self.Bind(wx.EVT_TOOL, self.OnDirectConnector, self.tools[14])
self.Bind(wx.EVT_TOOL, self.OnSquareConnector, self.tools[15])
self.Bind(wx.EVT_TOOL, self.OnLinearConnector, self.tools[16])
##################################################################### Abstraction hierarchy
self.Bind(wx.EVT_SPINCTRL, self.OnSpin, id=self.toggle_list[3])
self.Bind(wx.EVT_TEXT, self.OnSpin, id=self.toggle_list[3])
##############################################################################################
self.Bind(wx.EVT_TOOL, self.OnUpWard, id=ID_UPWARD)
self.Bind(wx.EVT_TOOL, self.OnDownWard, id=ID_DOWNWARD)
tb.Realize()
self.SetToolBar(tb)
def GetExportPathsList(self):
""" Return the list of exported path.
"""
return self.exportPathsList
def GetDiagramNotebook(self):
""" Return diagram notbook (right)
"""
return self.nb2
def GetControlNotebook(self):
""" Return control notebook (left)
"""
return self.nb1
def GetEditorPanel(self):
""" Return editor panel (rigth)
"""
return self.editor
def OnDirectConnector(self, event):
"""
"""
toolbar = event.GetEventObject()
for id in self.toggle_list:
toolbar.ToggleTool(id,0)
toolbar.ToggleTool(event.GetId(),1)
canvas = Container.ShapeCanvas
canvas.CONNECTOR_TYPE = 'direct'
#canvas.OnRefreshModel(canvas, event)
def OnSquareConnector(self, event):
"""
"""
self.OnDirectConnector(event)
canvas = Container.ShapeCanvas
canvas.CONNECTOR_TYPE = 'square'
def OnLinearConnector(self, event):
"""
"""
self.OnDirectConnector(event)
canvas = Container.ShapeCanvas
canvas.CONNECTOR_TYPE = 'linear'
def OnPaneClose(self, event):
""" Close pane has been invoked.
"""
caption = event.GetPane().caption
if caption in ["Control", 'Editor', 'Shell']:
msg = _("You realy want to close this pane?")
dlg = wx.MessageDialog(self, msg, _("Question"),
wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
event.Veto()
else:
menuItemList = []
menu = self.GetMenuBar().GetMenu(2)
if caption == 'Shell':
menuItemList.append(menu.FindItemById(Menu.ID_SHOW_SHELL))
elif caption == 'Editor':
menuItemList.append(menu.FindItemById(Menu.ID_SHOW_EDITOR))
else:
menuItemList.append(menu.FindItemById(Menu.ID_SHOW_LIB))
menuItemList.append(menu.FindItemById(Menu.ID_SHOW_PROP))
menuItemList.append(menu.FindItemById(Menu.ID_SHOW_SIM))
for menu_item in menuItemList:
getattr(menu_item, 'Check')(False)
dlg.Destroy()
###
def OnOpenRecentFile(self, event):
""" Recent file has been invoked.
"""
id = event.GetId()
#menu=event.GetEventObject()
##on Linux, event.GetEventObject() returns a reference to the menu item,
##while on Windows, event.GetEventObject() returns a reference to the main frame.
### before Phoenix transition
#menu = self.GetMenuBar().FindItemById(id).GetMenu()
#menuItem = menu.FindItemById(id)
### after Phoenix transition
menu = self.GetMenuBar().FindItemById(Menu.ID_RECENT).GetMenu()
menuItem = menu.FindItemById(id)
path = menuItem.GetItemLabel()
if path.endswith(('.dsp','.yaml')):
name = os.path.basename(path)
diagram = Container.Diagram()
#diagram.last_name_saved = path
open_file_result = diagram.LoadFile(path)
if isinstance(open_file_result, Exception):
wx.MessageBox(_('Error opening file.\nInfo : %s')%str(open_file_result), _('Error'), wx.OK | wx.ICON_ERROR)
else:
self.nb2.AddEditPage(os.path.splitext(name)[0], diagram)
self.EnableAbstractionButton()
def EnableAbstractionButton(self):
""" Enable DAM and UAM button depending of the abstraction level
"""
### update text filed
level = self.spin.GetValue()
### update doward and upward button
tb = self.GetToolBar()
flag = level != 0
tb.EnableTool(self.toggle_list[4], flag)
tb.EnableTool(self.toggle_list[5], flag)
def OnDeleteRecentFiles(self, event):
""" Delete the recent files list
"""
# update openFileList variable
self.openFileList = ['']*NB_OPENED_FILE
# update config file
self.cfg.Write("openFileList", str(eval("self.openFileList")))
self.cfg.Flush()
def OnCreatePerspective(self, event):
"""
"""
dlg = wx.TextEntryDialog(self, _("Enter a new perspective:"), _("Perspective Manager"), _("Perspective %d")%(len(self.perspectives)))
if dlg.ShowModal() == wx.ID_OK:
txt = dlg.GetValue()
if len(self.perspectives) == 0:
self.perspectivesmenu.AppendSeparator()
ID = wx.NewIdRef()
self.perspectivesmenu.Append(ID, txt)
self.perspectives[txt] = self._mgr.SavePerspective()
### Disable the delete function
self.perspectivesmenu.FindItemById(Menu.ID_DELETE_PERSPECTIVE).Enable(True)
### Bind right away to make activable the perspective without restart DEVSimPy
self.Bind(wx.EVT_MENU, self.OnRestorePerspective, id=ID)
NotificationMessage(_('Information'), _('%s has been added!')%txt, parent=self, timeout=5)
dlg.Destroy()
def OnRestorePerspective(self, event):
"""
"""
id = event.GetId()
item = self.GetMenuBar().FindItemById(id)
mgr = self.GetMGR()
mgr.LoadPerspective(self.perspectives[item.GetItemLabelText()])
def OnDeletePerspective(self, event):
"""
"""
# delete all path items
L = list(self.perspectivesmenu.GetMenuItems())
for item in L[4:]:
self.perspectivesmenu.Remove(item)
# update config file
self.perspectives = {_("Default Startup"):self._mgr.SavePerspective()}
self.cfg.Write("perspectives", str(eval("self.perspectives")))
self.cfg.Flush()
### Disable the delete function
self.perspectivesmenu.FindItemById(Menu.ID_DELETE_PERSPECTIVE).Enable(False)
NotificationMessage(_('Information'), _('All perspectives have been deleted!'), parent=self, timeout=5)
###
def OnDragInit(self, event):
"""
"""
# version avec arbre
item = event.GetItem()
tree = event.GetEventObject()
### in posix-based we drag only item (in window is automatic)
platform_sys = os.name
flag = True
if platform_sys == 'posix':
flag = tree.IsSelected(item)
# Dnd uniquement sur les derniers fils de l'arbre
if not tree.ItemHasChildren(item) and flag:
text = tree.GetItemPyData(event.GetItem()) if wx.VERSION_STRING < '4.0' else tree.GetItemData(event.GetItem())
try:
tdo = wx.PyTextDataObject(text) if wx.VERSION_STRING < '4.0' else wx.TextDataObject(text)
#tdo = wx.TextDataObject(text)
tds = wx.DropSource(tree)
tds.SetData(tdo)
tds.DoDragDrop(True)
except:
sys.stderr.write(_("OnDragInit avorting \n"))
###
def OnIdle(self, event):
"""
"""
if self.otherWin:
self.otherWin.Raise()
self.otherWin = None
###
def SaveLibraryProfile(self):
""" Update config file with the librairies opened during the last use of DEVSimPy.
"""
### Show is in position 2 on Menu Bar
show_menu = self.menuBar.GetMenu(2)
### Control is in position 1
control_item = show_menu.FindItemByPosition(0)
### Libraries is in position 2
libraries_item = control_item.GetSubMenu().FindItemByPosition(2)
### if Libraries tab is not visible in DEVSimPy (in nb1), don't save the configuration of libraries
if libraries_item.IsChecked():
# save in config file the opened last library directory
L = self.tree.GetItemChildren(self.tree.root)
self.cfg.Write("ChargedDomainList", str([k for k in self.tree.ItemDico if self.tree.ItemDico[k] in L]))
self.cfg.Flush()
def SavePerspectiveProfile(self):
""" Update the config file with the profile that are enabled during the last use of DEVSimPy
"""
# save in config file the last activated perspective
self.cfg.Write("perspectives", str(self.perspectives))
self.cfg.Flush()
def SaveBuiltinDict(self):
""" Save the specific builtin variable into the config file
"""
self.cfg.Write("builtin_dict", str(eval('dict((k, builtins.__dict__[k]) for k in builtin_dict)')))
self.cfg.Flush()
def SavePosition(self):
self.cfg.Write("last_position", str(self.GetPosition()))
self.cfg.Flush()
def SaveSize(self):
self.cfg.Write("last_size", str(self.GetSize()))
self.cfg.Flush()
###
def OnCloseWindow(self, event):
""" Close icon has been pressed. Closing DEVSimPy.
"""
exit = False
### for all pages, we invoke their OnClosePage function
for i in range(self.nb2.GetPageCount()):
### select the first page
self.nb2.SetSelection(0)
if not self.nb2.OnClosePage(event):
exit = True
break
if not exit:
### Save process
self.SaveLibraryProfile()
self.SavePerspectiveProfile()
self.SaveBuiltinDict()
self.SavePosition()
self.SaveSize()
self._mgr.UnInit()
del self._mgr
#self.Close()
#win = wx.Window_FindFocus()
#if win != None:
## Note: you really have to use wx.wxEVT_KILL_FOCUS
## instead of wx.EVT_KILL_FOCUS here:
#win.Disconnect(-1, -1, wx.wxEVT_KILL_FOCUS)
#self.Destroy()
event.Skip()
def OnSpin(self, event):
""" Spin button has been invoked (on the toolbar of the main windows or detached frame).
"""
### spin control object
spin = event.GetEventObject()
### get toolbar dynamically from frame
tb = spin.GetParent()