File: processdialog.py

package info (click to toggle)
sumo 1.18.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,218,476 kB
  • sloc: xml: 2,488,246; cpp: 431,611; python: 236,255; java: 14,424; cs: 5,200; ansic: 494; sh: 474; makefile: 80; csh: 1
file content (498 lines) | stat: -rw-r--r-- 19,396 bytes parent folder | download
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
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
# Copyright (C) 2016-2023 German Aerospace Center (DLR) and others.
# SUMOPy module
# Copyright (C) 2012-2021 University of Bologna - DICAM
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0/
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the Eclipse
# Public License 2.0 are satisfied: GNU General Public License, version 2
# or later which is available at
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later

# @file    processdialog.py
# @author  Joerg Schweizer
# @date    2012


import wx
import os
import objpanel
from wxmisc import AgileStatusbar


class ProcessDialogMixin:

    def get_status(self):
        return self.process.status

    def clear_log(self):
        self.get_logger().w('', 'message')
        self.get_logger().w('', 'action')

    def copy_options_to_results(self, results):
        # TODO
        pass

    def on_save_options(self, event):
        """
        Save current options to file.
        """
        dlg = wx.FileDialog(
            self, message="Save Options as ...",
            # defaultDir=os.getcwd(),
            # defaultFile="",
            wildcard='Python obj files (*.obj)|*.obj|All files (*.*)|*.*',
            style=wx.SAVE | wx.CHANGE_DIR
        )

        # This sets the default filter that the user will initially see. Otherwise,
        # the first filter in the list will be used by default.
        dlg.SetFilterIndex(0)

        # Show the dialog and retrieve the user response. If it is the OK response,
        # process the data.
        if dlg.ShowModal() == wx.ID_OK:
            filepath = dlg.GetPath()
            self.process.save_options(filepath)

    def on_load_options(self, event):
        """
        Load previously saved options from file. 
        """

        dlg = wx.FileDialog(self, message="Open object",
                            # defaultDir=os.getcwd(),
                            # defaultFile="",
                            wildcard='Python obj files (*.obj)|*.obj|All files (*.*)|*.*',
                            style=wx.OPEN | wx.CHANGE_DIR
                            )

        # Show the dialog and retrieve the user response. If it is the OK response,
        # process the data.
        if dlg.ShowModal() == wx.ID_OK:
            # This returns a Python list of files that were selected.
            filepath = dlg.GetPath()
            self.process.load_options(filepath)

        self.restore()


class ProcessDialog(ProcessDialogMixin, objpanel.ObjPanelDialog):
    def __init__(self, parent,
                 process,
                 attrconfigs=None,
                 tables=None,
                 table=None, id=None, ids=None,
                 groupnames=None, show_groupnames=False,
                 title=None, size=wx.DefaultSize, pos=wx.DefaultPosition,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
                 choose_id=False, choose_attr=False,
                 func_choose_id=None, func_change_obj=None, panelstyle='default',
                 immediate_apply=True):

        self.process = process
        if title is None:
            title = process.get_name()

        buttons, defaultbutton, standartbuttons = self._get_buttons()

        objpanel.ObjPanelDialog.__init__(self, parent, process,
                                         attrconfigs=None,
                                         id=None, ids=None,
                                         groupnames=['options', 'inputparameters'],
                                         show_groupnames=False,
                                         title=title, size=(800, 400), pos=wx.DefaultPosition,
                                         style=wx.DEFAULT_DIALOG_STYLE | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
                                         choose_id=False, choose_attr=False,
                                         func_choose_id=None,
                                         func_change_obj=None,
                                         panelstyle='default',
                                         immediate_apply=immediate_apply,
                                         buttons=buttons,
                                         standartbuttons=standartbuttons,
                                         defaultbutton=defaultbutton,
                                         )

    def _get_buttons(self):
        buttons = [('Run',   self.on_run,      'Start the process!'),
                   #('Kill',   self.on_kill,      'Kill process in background.'),
                   ('Apply',   self.on_apply,      'Apply current options, complete them and make them consistent, but do not run.'),
                   ('Save Options...', self.on_save_options, self.on_save_options.__doc__),
                   ('Load Options...', self.on_load_options, self.on_load_options.__doc__),
                   ]
        defaultbutton = 'Run'
        standartbuttons = ['cancel', ]

        return buttons, defaultbutton, standartbuttons

    def get_process(self):
        return self.process

    def on_run(self, event=None):
        self.on_apply()
        self.process.run()
        if self.process.status == 'success':
            self.Destroy()

    def on_kill(self, event=None):
        self.process.kill()

    def on_apply(self, event=None):
        self.process.update_params()
        self.restore()

    def recreate_panel_proc(self, obj=None,
                            attrconfigs=None,
                            tables=None,
                            table=None, id=None, ids=None,
                            groupnames=None, show_groupnames=False,
                            show_title=True,
                            is_modal=False,
                            immediate_apply=False,
                            panelstyle='default',
                            func_change_obj=None,
                            func_choose_id=None,
                            func_choose_attr=None,
                            **buttonargs):
        """
        Recreates panel and destroys previous contents:
            attr = a list ith attribute names to be shown
            groups = list with group names to be shown
            show_groupnames = the group names are shown 
                              together with the respective attributes
            is_modal = if true the panel will be optimized for dialog window
            immediate_apply = changes to widgets will be immediately applied to 
                                obj attribute without pressing apply
            buttonargs = a dictionary with arguments for botton creation
                    obj = the object to be displayed
            id = used if there is only one single id to be displayed
            ids = used if a selection of ids need to be displayed
            func_change_obj = function to be called if user clicks on on object
                                with obj as argument
            func_choose_id = function to be called when user clicks on id(table row)
                                with id as argument
            func_choose_attr = function to be called when user clicks on attribute 
                                with attr as argument. In this case the attribute
                                names of scalars turn into buttons. Array attributes
                                are selected by clicking on the column name. 
        """
        # print 'ProcessDialog.recreate_panel',groupnames
        # for attrconfig in obj.get_attrman().get_configs():
        #   print '  attrconfig.attrname',attrconfig.attrname
        #self.id = id
        #self.ids = ids
        self.obj = obj
        self.func_change_obj = func_change_obj
        self.func_choose_id = func_choose_id
        self.func_choose_attr = func_choose_attr
        self._show_title = show_title

        if (attrconfigs is None) & (tables in (None, [])) & (table is None):
            attrconfigs = obj.get_attrman().get_configs()
            if not self._show_title:
                # titels of groupname are not shown so just
                # select attributes at this stage
                attrconfig_new = []
                for attrconfig in attrconfigs:
                    # print '  attrconfig.attrname',attrconfig.attrname
                    is_shown = False
                    for groupname in attrconfig.groupnames:
                        # print ' comp:',attrconfig.attrname,groupname,groupname in groupnames
                        if groupname in groupnames:
                            is_shown = True
                            break

                    if is_shown:
                        attrconfig_new.append(attrconfig)
                attrconfigs = attrconfig_new

        tables = None  # obj.get_tablemans()

        # print 'is_scalar_panel & is_multitab'

        sizer = self.init_notebook()
        self.add_scalarpage(attrconfigs=attrconfigs, groupnames=groupnames,
                            id=id, immediate_apply=immediate_apply, panelstyle=panelstyle,
                            is_modal=is_modal, show_title=show_title,
                            show_buttons=False, **buttonargs)

        for table in tables:
            self.add_tablepage(table, groupnames=groupnames)

        self.show_notebook()
        sizer = self.GetSizer()
        self.add_buttons(self, sizer,
                         is_modal=is_modal,
                         **buttonargs)
        # some widgets like color need this to expand into their maximum space
        self.restore()
        return True


class ProcessDialogInteractive(ProcessDialogMixin, wx.Frame):

    """
    A frame used for the ObjBrowser Demo

    """

    def __init__(self, parent,
                 process,
                 title=None,
                 func_close=None,
                 is_close_after_completion=True,
                 ):

        if title is None:
            title = process.get_name()
        wx.Frame.__init__(self, parent, -1, title=title, pos=wx.DefaultPosition, size=wx.DefaultSize)

        self.parent = parent
        self.process = process

        self.func_close = func_close
        # if self.func_close is None:
        self.is_close_after_completion = is_close_after_completion
        # else:
        #    self.is_close_after_completion = False
        #self._is_run = False

        self.Bind(wx.EVT_TIMER, self.on_step)
        self.timer = wx.Timer(self)
        # Set up the MenuBar
        #MenuBar = wx.MenuBar()
        #file_menu = wx.Menu()
        #item = file_menu.Append(-1, "&Import CSV...","Import OD data from a CSV text file with format <zonename orig>, <zonename dest>,<number of trips>")
        #self.Bind(wx.EVT_MENU, self.on_import_csv, item)
        #item = file_menu.Append(-1, "&Import Exel...","Import OD data from an Exel file.")
        #self.Bind(wx.EVT_MENU, self.on_import_exel, item)
        #help_menu = wx.Menu()
        # item = help_menu.Append(-1, "&About",
        #                        "More information About this program")
        #self.Bind(wx.EVT_MENU, self.on_menu, item)
        #MenuBar.Append(help_menu, "&Help")
        # self.SetMenuBar(MenuBar)

        #################################################################
        # create statusbar
        #self.statusbar = AgileStatusbar(self)
        self.statusbar = AgileStatusbar(self, fields=[  # ('action',-4),
                                        ('message', -10),
                                        # ('coords',-1),
                                        # ('zoom',-1),
                                        ('progress', -3),
                                        ('status', -1),
                                        # ('coords',-1),
                                        ])
        self.SetStatusBar(self.statusbar)
        # self.count=0.0

        logger = process.get_logger()
        self.oldprogressfunc = logger.get_clallbackfunc('progress')
        logger.add_callback(self.show_progress, 'progress')

        self.oldmessagefunc = logger.get_clallbackfunc('message')
        logger.add_callback(self.write_message, 'message')

        #################################################################
        # create toolbar

        # self.init_toolbar(size=size_toolbaricons)

        self.browser = self.make_browser()

        # Create a sizer to manage the Canvas and message window
        MainSizer = wx.BoxSizer(wx.VERTICAL)
        MainSizer.Add(self.browser, 4, wx.EXPAND)

        self.SetSizer(MainSizer)
        self.Bind(wx.EVT_CLOSE, self.on_close)
        #self.Bind(wx.EVT_IDLE, self.on_idle)

        self.EventsAreBound = False

        # getting all the colors for random objects
        # wxlib.colourdb.updateColourDB()
        #self.colors = wxlib.colourdb.getColourList()

        return None

    def _get_buttons(self):
        if hasattr(self.process, 'step'):
            buttons = [('Start',   self.on_start,      'Start the process!'),
                       ('Stop',   self.on_stop,        'Stop process.'),
                       ('Step',   self.on_singlestep,      'Make a single step.'),
                       ('Done',   self.on_done,        'Stop process and close window.'),
                       ]
            defaultbutton = 'Start'

        else:
            if self.is_close_after_completion:
                buttons = [('Run',   self.on_start,      'Start the process!'),
                           ]
            else:
                buttons = [('Run',   self.on_start,      'Start the process!'),
                           ('Done',   self.on_done,      'Finish with process and close window.'),
                           ]
            defaultbutton = 'Run'

        buttons.append(('Cancel',   self.on_close,        'Close window, without running the process.'))
        # standartbuttons=['cancel'] # uses also standard on_cancel :(
        standartbuttons = []
        return buttons, defaultbutton, standartbuttons

    # def on_idle(self,event):
    #    print 'on_idle'
    #
    #    if self._is_run:
    #        self.process.step()
    #        if self.process.status=='success':
    #            self._is_run = False
    #            self.Destroy()

    def on_start(self, event=None):
        self.browser.apply()
        if self.process.status != 'running':
            self.process.update_params()
            # self.refresh_browser()

            # TODO: check whether to use ALWAYS run to put process in running mode
            if hasattr(self.process, 'step'):
                self.process.do()
            else:
                self.process.run()

                # no closing function defined
                if self.is_close_after_completion:
                    self.on_close(event)

            # print 'on_start: after preparation self.process.status=',self.process.status

        if hasattr(self.process, 'step'):
            self.timer.Start(1)

        # while  self.process.status=='running':
        #    print 'call step'
        #    self.process.step()

        # if self.process.status=='running':
        #    # this will call step method in on_idle
        #    self._is_run = True
        #
        # elif self.process.status=='preparation':
        #    self.process.update_params()
        #    self.refresh_browser()
        #    self.process.run()

    def on_step(self, event=None):
        if self.process.status == 'running':
            # print 'call step'
            self.process.step()
        else:
            print('  Simulation finished')
            self.timer.Stop()

    def on_stop(self, event=None):
        self.timer.Stop()

    def on_singlestep(self, event=None):
        if self.process.status == 'running':
            if hasattr(self.process, 'step'):
                wx.FutureCall(1, self.process.step)

    def on_close(self, event=None):
        # print 'on_close',self.process.status
        if self.process.status == 'running':
            self.process.aboard()
            # print '  aboarded.'

        self.MakeModal(False)
        # print '  call func_close',self.func_close
        if self.func_close is not None:
            self.func_close(self)

        # print '  reput callbacks to main'
        if self.oldprogressfunc is not None:
            self.process.get_logger().add_callback(self.oldprogressfunc, 'progress')

        if self.oldmessagefunc is not None:
            self.process.get_logger().add_callback(self.oldmessagefunc, 'message')

        # print '  call destroy'
        self.Destroy()
        # self.Close() # no effect

    def on_done(self, event=None):
        # print 'on_done',self.process.status
        self.on_close(event)

    def on_cancel(self, event):
        """
        Apply values, destroy itself and parent
        """
        # print 'on_cancel'
        self.on_close(event)

    def on_kill(self, event=None):
        # self.process.kill()
        pass

    def show_progress(self, percent, **kwargs):
        """
        Shows progress on progress bar. Plug-in funcion for logger.
        """
        # print 'show_progress',percent
        self.statusbar.set_progress(percent)
        # self.Refresh()
        # wx.Yield()
        # self.Update()

    def write_message(self, text, **kwargs):
        print('write_message', text)
        self.statusbar.write_message(text)

    def make_browser(self):

        buttons, defaultbutton, standartbuttons = self._get_buttons()
        browser = objpanel.ObjPanel(self, self.process,
                                    attrconfigs=None,
                                    id=None, ids=None,
                                    groupnames=['options', 'inputparameters'],
                                    func_change_obj=None,
                                    show_groupnames=False, show_title=False,
                                    is_modal=True,
                                    mainframe=None,
                                    pos=wx.DefaultPosition,
                                    size=wx.DefaultSize,
                                    style=wx.MAXIMIZE_BOX | wx.RESIZE_BORDER,
                                    immediate_apply=False,  # True,
                                    panelstyle='default',
                                    buttons=buttons,
                                    standartbuttons=standartbuttons,
                                    defaultbutton=defaultbutton,
                                    )
        return browser

    def refresh_browser(self):
        """
        Deletes previous conents 
        Builds panel for obj
        Updates path window and history
        """
        # print 'Wizzard.refresh_panel with',obj.ident
        # remove previous obj panel
        sizer = self.GetSizer()
        sizer.Remove(0)
        self.browser.Destroy()
        #del self.browser
        self.browser = self.make_browser()

        sizer.Add(self.browser, 1, wx.GROW)

        self.Refresh()
        # sizer.Fit(self)
        sizer.Layout()
        # add to history