~ubuntu-branches/ubuntu/raring/wxwidgets2.8/raring

« back to all changes in this revision

Viewing changes to wxPython/wx/tools/Editra/plugins/Launch/launch/launch.py

  • Committer: Package Import Robot
  • Author(s): Stéphane Graber
  • Date: 2012-01-07 13:59:25 UTC
  • mfrom: (1.1.9) (5.1.10 sid)
  • Revision ID: package-import@ubuntu.com-20120107135925-2601miy9ullcon9j
Tags: 2.8.12.1-6ubuntu1
* Resync from Debian, changes that were kept:
  - debian/rules: re-enable mediactrl. This allows libwx_gtk2u_media-2.8 to be
    built, as this is required by some applications (LP: #632984)
  - debian/control: Build-dep on libxt-dev for mediactrl.
  - Patches
    + fix-bashism-in-example
* Add conflict on python-wxgtk2.8 (<< 2.8.12.1-6ubuntu1~) to python-wxversion
  to guarantee upgrade ordering when moving from pycentral to dh_python2.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 
10
10
"""Launch User Interface"""
11
11
__author__ = "Cody Precord <cprecord@editra.org>"
12
 
__svnid__ = "$Id: launch.py 63427 2010-02-09 00:11:11Z CJP $"
13
 
__revision__ = "$Revision: 63427 $"
14
 
__version__ = "0.1"
 
12
__svnid__ = "$Id: launch.py 67778 2011-05-23 20:58:56Z CJP $"
 
13
__revision__ = "$Revision: 67778 $"
15
14
 
16
15
#-----------------------------------------------------------------------------#
17
16
# Imports
25
24
 
26
25
# Editra Libraries
27
26
import ed_glob
 
27
import ed_basestc
28
28
import util
29
29
from profiler import Profile_Get, Profile_Set
30
30
import ed_txt
31
31
import ed_msg
32
32
import ebmlib
33
33
import eclib
 
34
import ed_basewin
34
35
 
35
36
#-----------------------------------------------------------------------------#
36
37
# Globals
37
 
ID_SETTINGS = wx.NewId()
38
38
ID_EXECUTABLE = wx.NewId()
39
39
ID_ARGS = wx.NewId()
40
 
ID_RUN = wx.NewId()
41
40
 
42
41
# Profile Settings Key
43
 
LAUNCH_KEY = 'Launch.Config'
44
42
#LAUNCH_PREFS = 'Launch.Prefs' # defined in cfgdlg
45
43
 
46
44
# Custom Messages
55
53
_ = wx.GetTranslation
56
54
#-----------------------------------------------------------------------------#
57
55
 
58
 
def OnStoreConfig(msg):
59
 
    Profile_Set(LAUNCH_KEY, handlers.GetState())
60
 
ed_msg.Subscribe(OnStoreConfig, cfgdlg.EDMSG_LAUNCH_CFG_EXIT)
61
 
 
62
56
def OnRegisterHandler(msg):
63
57
    """Register a custom handler
64
58
    @param msg: dict(xml=xml_str, loaded=bool)
73
67
 
74
68
#-----------------------------------------------------------------------------#
75
69
 
76
 
class LaunchWindow(eclib.ControlBox):
 
70
class LaunchWindow(ed_basewin.EdBaseCtrlBox):
77
71
    """Control window for showing and running scripts"""
78
72
    def __init__(self, parent):
79
 
        eclib.ControlBox.__init__(self, parent)
 
73
        super(LaunchWindow, self).__init__(parent)
80
74
 
81
75
        # Attributes
82
76
        self._log = wx.GetApp().GetLog()
83
 
        self._mw = self.__FindMainWindow()
 
77
        self._mw = ed_basewin.FindMainWindow(self)
84
78
        self._buffer = OutputDisplay(self)
85
79
        self._fnames = list()
86
 
        self._chFiles = None # Created in __DoLayout
 
80
        self._run = None        # Created in __DoLayout
 
81
        self._pbtn = None       # Created in __DoLayout
 
82
        self._clear = None      # Created in __DoLayout
 
83
        self._lockFile = None   # Created in __DoLayout
 
84
        self._chFiles = None    # Created in __DoLayout
87
85
        self._worker = None
88
86
        self._busy = False
89
87
        self._isready = False
90
 
        self._config = dict(file='', lang=0,
91
 
                            cfile='', clang=0,
92
 
                            last='', lastlang=0,
93
 
                            prelang=0, largs='',
94
 
                            lcmd='')
95
 
        self._prefs = Profile_Get(cfgdlg.LAUNCH_PREFS, default=None)
 
88
        self._state = dict(file='', lang=0, cfile='', clang=0, last='', 
 
89
                           lastlang=0, prelang=0, largs='', lcmd='')
96
90
 
97
91
        # Setup
98
92
        self.__DoLayout()
99
93
        if not handlers.InitCustomHandlers(ed_glob.CONFIG['CACHE_DIR']):
100
94
            util.Log(u"[launch][warn] failed to load launch extensions")
101
95
 
102
 
        hstate = Profile_Get(LAUNCH_KEY)
103
 
        if hstate is not None:
104
 
            handlers.SetState(hstate)
105
 
        if self._prefs is None:
106
 
            Profile_Set(cfgdlg.LAUNCH_PREFS,
107
 
                        dict(autoclear=False,
108
 
                             errorbeep=False,
109
 
                             defaultf=self._buffer.GetDefaultForeground().Get(),
110
 
                             defaultb=self._buffer.GetDefaultBackground().Get(),
111
 
                             errorf=self._buffer.GetErrorForeground().Get(),
112
 
                             errorb=self._buffer.GetErrorBackground().Get(),
113
 
                             infof=self._buffer.GetInfoForeground().Get(),
114
 
                             infob=self._buffer.GetInfoBackground().Get(),
115
 
                             warnf=self._buffer.GetWarningForeground().Get(),
116
 
                             warnb=self._buffer.GetWarningBackground().Get()))
117
 
            self._prefs = Profile_Get(cfgdlg.LAUNCH_PREFS)
 
96
        # Ensure preferences have been initialized
 
97
        cfgdlg.InitConfig()
118
98
 
119
 
        self._buffer.SetPrefs(self._prefs)
120
99
        self.UpdateBufferColors()
121
 
        cbuffer = self._mw.GetNotebook().GetCurrentCtrl()
 
100
        cbuffer = GetTextBuffer(self.MainWindow)
122
101
        self.SetupControlBar(cbuffer)
123
 
        self._config['lang'] = GetLangIdFromMW(self._mw)
124
 
        self.UpdateCurrentFiles(self._config['lang'])
125
 
        self.SetFile(GetTextBuffer(self._mw).GetFileName())
 
102
        self.State['lang'] = GetLangIdFromMW(self.MainWindow)
 
103
        self.UpdateCurrentFiles(self.State['lang'])
 
104
        self.SetFile(cbuffer.GetFileName())
126
105
 
127
106
        # Setup filetype settings
128
107
        self.RefreshControlBar()
130
109
        # Event Handlers
131
110
        self.Bind(wx.EVT_BUTTON, self.OnButton)
132
111
        self.Bind(wx.EVT_CHOICE, self.OnChoice)
 
112
        self.Bind(wx.EVT_CHECKBOX, self.OnCheck)
 
113
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy, self)
133
114
        ed_msg.Subscribe(self.OnPageChanged, ed_msg.EDMSG_UI_NB_CHANGED)
134
115
        ed_msg.Subscribe(self.OnFileOpened, ed_msg.EDMSG_FILE_OPENED)
135
116
        ed_msg.Subscribe(self.OnThemeChanged, ed_msg.EDMSG_THEME_CHANGED)
136
117
        ed_msg.Subscribe(self.OnLexerChange, ed_msg.EDMSG_UI_STC_LEXER)
137
 
        ed_msg.Subscribe(self.OnConfigExit, cfgdlg.EDMSG_LAUNCH_CFG_EXIT)
 
118
        ed_msg.Subscribe(self.OnConfigChange,
 
119
                         ed_msg.EDMSG_PROFILE_CHANGE + (handlers.CONFIG_KEY,))
138
120
        ed_msg.Subscribe(self.OnRunMsg, MSG_RUN_LAUNCH)
139
121
        ed_msg.Subscribe(self.OnRunLastMsg, MSG_RUN_LAST)
140
122
        ed_msg.RegisterCallback(self._CanLaunch, REQUEST_ACTIVE)
141
123
        ed_msg.RegisterCallback(self._CanReLaunch, REQUEST_RELAUNCH)
142
124
 
143
 
    def __del__(self):
144
 
        ed_msg.Unsubscribe(self.OnPageChanged)
145
 
        ed_msg.Unsubscribe(self.OnFileOpened)
146
 
        ed_msg.Unsubscribe(self.OnThemeChanged)
147
 
        ed_msg.Unsubscribe(self.OnLexerChange)
148
 
        ed_msg.Unsubscribe(self.OnConfigExit)
149
 
        ed_msg.Unsubscribe(self.OnRunMsg)
150
 
        ed_msg.Unsubscribe(self.OnRunLastMsg)
151
 
        ed_msg.UnRegisterCallback(self._CanLaunch)
152
 
        ed_msg.UnRegisterCallback(self._CanReLaunch)
153
 
        super(LaunchWindow, self).__del__()
 
125
    #---- Properties ----#
 
126
    Locked = property(lambda self: self._lockFile.IsChecked())
 
127
    MainWindow = property(lambda self: self._mw)
 
128
    Preferences = property(lambda self: Profile_Get(handlers.CONFIG_KEY, default=None),
 
129
                           lambda self, prefs: Profile_Set(handlers.CONFIG_KEY, prefs))
 
130
    State = property(lambda self: self._state)
 
131
 
 
132
    def OnDestroy(self, evt):
 
133
        if self:
 
134
            ed_msg.Unsubscribe(self.OnPageChanged)
 
135
            ed_msg.Unsubscribe(self.OnFileOpened)
 
136
            ed_msg.Unsubscribe(self.OnThemeChanged)
 
137
            ed_msg.Unsubscribe(self.OnLexerChange)
 
138
            ed_msg.Unsubscribe(self.OnConfigChange)
 
139
            ed_msg.Unsubscribe(self.OnRunMsg)
 
140
            ed_msg.Unsubscribe(self.OnRunLastMsg)
 
141
            ed_msg.UnRegisterCallback(self._CanLaunch)
 
142
            ed_msg.UnRegisterCallback(self._CanReLaunch)
154
143
 
155
144
    def __DoLayout(self):
156
145
        """Layout the window"""
157
 
        #-- Setup ControlBar --#
158
 
        ctrlbar = eclib.ControlBar(self, style=eclib.CTRLBAR_STYLE_GRADIENT)
159
 
        if wx.Platform == '__WXGTK__':
160
 
            ctrlbar.SetWindowStyle(eclib.CTRLBAR_STYLE_DEFAULT)
 
146
        ctrlbar = self.CreateControlBar(wx.TOP)
161
147
 
162
148
        # Preferences
163
 
        prefbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_PREF), wx.ART_MENU)
164
 
        pref = eclib.PlateButton(ctrlbar, ID_SETTINGS, '', prefbmp,
165
 
                                 style=eclib.PB_STYLE_NOBG)
166
 
        pref.SetToolTipString(_("Settings"))
167
 
        ctrlbar.AddControl(pref, wx.ALIGN_LEFT)
 
149
        self._pbtn = self.AddPlateButton(u"", ed_glob.ID_PREF)
 
150
        self._pbtn.SetToolTipString(_("Settings"))
168
151
 
169
152
        # Exe
170
153
        ctrlbar.AddControl(wx.StaticText(ctrlbar, label=_("exec") + ":"),
175
158
 
176
159
        # Script Label
177
160
        ctrlbar.AddControl((5, 5), wx.ALIGN_LEFT)
 
161
        self._lockFile = wx.CheckBox(ctrlbar, wx.ID_ANY)
 
162
        self._lockFile.SetToolTipString(_("Lock File"))
 
163
        ctrlbar.AddControl(self._lockFile, wx.ALIGN_LEFT)
178
164
        self._chFiles = wx.Choice(ctrlbar, wx.ID_ANY)#, choices=[''])
179
165
        ctrlbar.AddControl(self._chFiles, wx.ALIGN_LEFT)
180
166
 
182
168
        ctrlbar.AddControl((5, 5), wx.ALIGN_LEFT)
183
169
        ctrlbar.AddControl(wx.StaticText(ctrlbar, label=_("args") + ":"),
184
170
                           wx.ALIGN_LEFT)
185
 
        args = wx.TextCtrl(ctrlbar, ID_ARGS)
186
 
        args.SetToolTipString(_("Script Arguments"))
187
 
        ctrlbar.AddControl(args, wx.ALIGN_LEFT)
 
171
        args = wx.TextCtrl(ctrlbar, ID_ARGS, size=(100,-1))
 
172
        args.SetToolTipString(_("Arguments"))
 
173
        ctrlbar.AddControl(args, wx.ALIGN_LEFT, 1)
188
174
 
189
175
        # Spacer
190
176
        ctrlbar.AddStretchSpacer()
191
177
        
192
 
        # Run Button
193
 
        rbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_BIN_FILE), wx.ART_MENU)
194
 
        if rbmp.IsNull() or not rbmp.IsOk():
195
 
            rbmp = None
196
 
        run = eclib.PlateButton(ctrlbar, ID_RUN, _("Run"), rbmp,
197
 
                                style=eclib.PB_STYLE_NOBG)
198
 
        ctrlbar.AddControl(run, wx.ALIGN_RIGHT)
199
 
 
200
 
        # Clear Button
201
 
        cbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DELETE), wx.ART_MENU)
202
 
        if cbmp.IsNull() or not cbmp.IsOk():
203
 
            cbmp = None
204
 
        clear = eclib.PlateButton(ctrlbar, wx.ID_CLEAR, _("Clear"),
205
 
                                  cbmp, style=eclib.PB_STYLE_NOBG)
206
 
        ctrlbar.AddControl(clear, wx.ALIGN_RIGHT)
207
 
        ctrlbar.SetVMargin(1, 1)
208
 
        self.SetControlBar(ctrlbar)
209
 
 
 
178
        # Buttons
 
179
        self._run = self.AddPlateButton(_("Run"), ed_glob.ID_BIN_FILE, 
 
180
                                        wx.ALIGN_LEFT)
 
181
        self._clear = self.AddPlateButton(_("Clear"), ed_glob.ID_DELETE,
 
182
                                          wx.ALIGN_RIGHT)
210
183
        self.SetWindow(self._buffer)
211
184
 
212
 
    def __FindMainWindow(self):
213
 
        """Find the mainwindow of this control
214
 
        @return: MainWindow or None
215
 
 
216
 
        """
217
 
        def IsMainWin(win):
218
 
            """Check if the given window is a main window"""
219
 
            return getattr(tlw, '__name__', '') == 'MainWindow'
220
 
 
221
 
        tlw = self.GetTopLevelParent()
222
 
        if IsMainWin(tlw):
223
 
            return tlw
224
 
        elif hasattr(tlw, 'GetParent'):
225
 
            tlw = tlw.GetParent()
226
 
            if IsMainWin(tlw):
227
 
                return tlw
228
 
 
229
 
        return None
230
 
 
231
185
    def _CanLaunch(self):
232
186
        """Method to use with RegisterCallback for getting status"""
233
187
        val = self.CanLaunch()
238
192
    def _CanReLaunch(self):
239
193
        """Method to use with RegisterCallback for getting status"""
240
194
        val = self.CanLaunch()
241
 
        if not val or not len(self._config['last']):
 
195
        if not val or not len(self.State['last']):
242
196
            val = ed_msg.NullValue()
243
197
        return val
244
198
 
247
201
        @return: bool
248
202
 
249
203
        """
250
 
        parent = self.GetParent()
251
 
        return parent.GetParent().IsActive() and self._isready
 
204
        return self.TopLevelParent.IsActive() and self._isready
252
205
 
253
206
    def GetFile(self):
254
207
        """Get the file that is currently set to be run
255
208
        @return: file path
256
209
 
257
210
        """
258
 
        return self._config['file']
 
211
        return self.State['file']
259
212
 
260
213
    def GetLastRun(self):
261
214
        """Get the last file that was run
262
215
        @return: (fname, lang_id)
263
216
 
264
217
        """
265
 
        return (self._config['last'], self._config['lastlang'])
266
 
 
267
 
    def GetMainWindow(self):
268
 
        """Get the mainwindow that created this instance
269
 
        @return: reference to MainWindow
270
 
 
271
 
        """
272
 
        return self._mw
 
218
        return (self.State['last'], self.State['lastlang'])
273
219
 
274
220
    def OnButton(self, evt):
275
221
        """Handle events from the buttons on the control bar"""
276
 
        e_id = evt.GetId()
277
 
        if e_id == ID_SETTINGS:
 
222
        e_obj = evt.GetEventObject()
 
223
        if e_obj == self._pbtn:
278
224
            app = wx.GetApp()
279
225
            win = app.GetWindowInstance(cfgdlg.ConfigDialog)
280
226
            if win is None:
281
 
                config = cfgdlg.ConfigDialog(self._mw)
 
227
                config = cfgdlg.ConfigDialog(self.MainWindow)
282
228
                config.CentreOnParent()
283
229
                config.Show()
284
230
            else:
285
231
                win.Raise()
286
 
        elif e_id == ID_RUN:
 
232
        elif e_obj is self._run:
287
233
            # May be run or abort depending on current state
288
234
            self.StartStopProcess()
289
 
        elif e_id == wx.ID_CLEAR:
 
235
        elif e_obj == self._clear:
290
236
            self._buffer.Clear()
291
237
        else:
292
238
            evt.Skip()
304
250
            self._chFiles.SetToolTipString(fname)
305
251
        elif e_id == ID_EXECUTABLE:
306
252
            e_obj = evt.GetEventObject()
307
 
            handler = handlers.GetHandlerById(self._config['lang'])
 
253
            handler = handlers.GetHandlerById(self.State['lang'])
308
254
            cmd = e_obj.GetStringSelection()
309
255
            e_obj.SetToolTipString(handler.GetCommand(cmd))
310
256
        else:
311
257
            evt.Skip()
312
258
 
313
 
    def OnConfigExit(self, msg):
314
 
        """Update current state when the config dialog has been closed
 
259
    def OnCheck(self, evt):
 
260
        """CheckBox for Lock File was clicked"""
 
261
        e_obj = evt.GetEventObject()
 
262
        if e_obj is self._lockFile:
 
263
            if self.Locked:
 
264
                self._chFiles.Disable()
 
265
            else:
 
266
                self._chFiles.Enable()
 
267
                cbuff = GetTextBuffer(self.MainWindow)
 
268
                if isinstance(cbuff, ed_basestc.EditraBaseStc):
 
269
                    self.UpdateCurrentFiles(cbuff.GetLangId())
 
270
                    self.SetupControlBar(cbuff)
 
271
        else:
 
272
            evt.Skip()
 
273
 
 
274
    def OnConfigChange(self, msg):
 
275
        """Update current state when the configuration has been changed
315
276
        @param msg: Message Object
316
277
 
317
278
        """
318
279
        util.Log("[Launch][info] Saving config to profile")
319
280
        self.RefreshControlBar()
320
 
        Profile_Set(LAUNCH_KEY, handlers.GetState())
 
281
        self._buffer.UpdateWrapMode()
321
282
        self.UpdateBufferColors()
322
283
 
323
284
    @ed_msg.mwcontext
326
287
        @param msg: Message Object
327
288
 
328
289
        """
 
290
        if self.Locked:
 
291
            return # Mode is locked ignore update
 
292
 
329
293
        # Update the file choice control
330
 
        self._config['lang'] = GetLangIdFromMW(self._mw)
331
 
        self.UpdateCurrentFiles(self._config['lang'])
 
294
        self.State['lang'] = GetLangIdFromMW(self.MainWindow)
 
295
        self.UpdateCurrentFiles(self.State['lang'])
332
296
 
333
297
        fname = msg.GetData()
334
298
        self.SetFile(fname)
345
309
 
346
310
        """
347
311
        self._log("[launch][info] Lexer changed handler - context %d" %
348
 
                  self._mw.GetId())
 
312
                  self.MainWindow.GetId())
 
313
 
 
314
        if self.Locked:
 
315
            return # Mode is locked ignore update
349
316
 
350
317
        mdata = msg.GetData()
351
318
        # For backwards compatibility with older message format
356
323
        # Update regardless of whether lexer has changed or not as the buffer
357
324
        # may have the lexer set before the file was saved to disk.
358
325
        if fname:
359
 
            #if ftype != self._config['lang']:
360
326
            self.UpdateCurrentFiles(ftype)
361
327
            self.SetControlBarState(fname, ftype)
362
328
 
 
329
    @ed_msg.mwcontext
363
330
    def OnPageChanged(self, msg):
364
331
        """Update the status of the currently associated file
365
332
        when the page changes in the main notebook.
366
333
        @param msg: Message object
367
334
 
368
335
        """
369
 
        # Only update when in the active window
370
 
        if not self._mw.IsActive():
 
336
        # The current mode is locked
 
337
        if self.Locked:
371
338
            return
372
339
 
373
340
        mval = msg.GetData()
374
341
        ctrl = mval[0].GetCurrentCtrl()
375
 
        self.UpdateCurrentFiles(ctrl.GetLangId())
376
 
        if hasattr(ctrl, 'GetFileName'):
 
342
        if isinstance(ctrl, ed_basestc.EditraBaseStc):
 
343
            self.UpdateCurrentFiles(ctrl.GetLangId())
377
344
            self.SetupControlBar(ctrl)
 
345
        else:
 
346
            self._log("[launch][info] Non STC object in notebook")
 
347
            return # Doesn't implement EdStc interface
378
348
 
379
349
    def OnRunMsg(self, msg):
380
350
        """Run or abort a launch process if this is the current 
383
353
 
384
354
        """
385
355
        if self.CanLaunch():
386
 
            shelf = self._mw.GetShelf()
 
356
            shelf = self.MainWindow.GetShelf()
387
357
            shelf.RaiseWindow(self)
388
358
            self.StartStopProcess()
389
359
 
398
368
            if not len(fname):
399
369
                return
400
370
 
401
 
            shelf = self._mw.GetShelf()
 
371
            shelf = self.MainWindow.GetShelf()
402
372
            self.UpdateCurrentFiles(ftype)
403
373
            self.SetFile(fname)
404
374
            self.RefreshControlBar()
405
375
            shelf.RaiseWindow(self)
406
376
 
407
 
            if self._prefs.get('autoclear'):
 
377
            if self.Preferences.get('autoclear'):
408
378
                self._buffer.Clear()
409
379
 
410
380
            self.SetProcessRunning(True)
411
381
 
412
 
            self.Run(fname, self._config['lcmd'], self._config['largs'], ftype)
 
382
            self.Run(fname, self.State['lcmd'], self.State['largs'], ftype)
413
383
 
414
384
    def OnThemeChanged(self, msg):
415
385
        """Update icons when the theme has been changed
416
386
        @param msg: Message Object
417
387
 
418
388
        """
419
 
        ctrls = ((ID_SETTINGS, ed_glob.ID_PREF),
420
 
                 (wx.ID_CLEAR, ed_glob.ID_DELETE))
 
389
        ctrls = ((self._pbtn, ed_glob.ID_PREF),
 
390
                 (self._clear, ed_glob.ID_DELETE))
421
391
        if self._busy:
422
 
            ctrls += ((ID_RUN, ed_glob.ID_STOP),)
 
392
            ctrls += ((self._run, ed_glob.ID_STOP),)
423
393
        else:
424
 
            ctrls += ((ID_RUN, ed_glob.ID_BIN_FILE),)
 
394
            ctrls += ((self._run, ed_glob.ID_BIN_FILE),)
425
395
 
426
 
        for ctrl, art in ctrls:
427
 
            btn = self.FindWindowById(ctrl)
 
396
        for btn, art in ctrls:
428
397
            bmp = wx.ArtProvider.GetBitmap(str(art), wx.ART_MENU)
429
398
            btn.SetBitmap(bmp)
430
399
            btn.Refresh()
 
400
        self.GetControlBar().Refresh()
431
401
 
432
402
    def RefreshControlBar(self):
433
403
        """Refresh the state of the control bar based on the current config"""
434
 
        handler = handlers.GetHandlerById(self._config['lang'])
 
404
        handler = handlers.GetHandlerById(self.State['lang'])
435
405
        cmds = handler.GetAliases()
436
406
 
437
407
        # Get the controls
438
408
        exe_ch = self.FindWindowById(ID_EXECUTABLE)
439
409
        args_txt = self.FindWindowById(ID_ARGS)
440
 
        run_btn = self.FindWindowById(ID_RUN)
441
410
 
442
 
        # Set control states
443
411
        csel = exe_ch.GetStringSelection()
444
412
        exe_ch.SetItems(cmds)
445
 
        if len(cmds):
 
413
        ncmds = len(cmds)
 
414
        if ncmds > 0:
446
415
            exe_ch.SetToolTipString(handler.GetCommand(cmds[0]))
447
416
 
448
 
        util.Log("[Launch][info] Found commands %s" % str(cmds))
449
 
        if handler.GetName() != handlers.DEFAULT_HANDLER and len(self.GetFile()):
450
 
            for ctrl in (exe_ch, args_txt, run_btn, self._chFiles):
 
417
        util.Log("[Launch][info] Found commands %s" % repr(cmds))
 
418
        if handler.GetName() != handlers.DEFAULT_HANDLER and \
 
419
           ncmds > 0 and len(self.GetFile()):
 
420
            for ctrl in (exe_ch, args_txt, self._run,
 
421
                         self._chFiles, self._lockFile):
451
422
                ctrl.Enable()
 
423
 
452
424
            self._isready = True
 
425
            if self.Locked:
 
426
                self._chFiles.Enable(False)
453
427
 
454
 
            if self._config['lang'] == self._config['prelang'] and len(csel):
 
428
            if self.State['lang'] == self.State['prelang'] and len(csel):
455
429
                exe_ch.SetStringSelection(csel)
456
430
            else:
457
431
                csel = handler.GetDefault()
461
435
            self.GetControlBar().Layout()
462
436
        else:
463
437
            self._isready = False
464
 
            for ctrl in (exe_ch, args_txt, run_btn, self._chFiles):
 
438
            for ctrl in (exe_ch, args_txt, self._run,
 
439
                         self._chFiles, self._lockFile):
465
440
                ctrl.Disable()
466
 
            self._chFiles.Clear()
467
441
 
468
442
    def Run(self, fname, cmd, args, ftype):
469
443
        """Run the given file
474
448
 
475
449
        """
476
450
        # Find and save the file if it is modified
477
 
        nb = self._mw.GetNotebook()
 
451
        nb = self.MainWindow.GetNotebook()
478
452
        for ctrl in nb.GetTextControls():
479
453
            tname = ctrl.GetFileName()
480
454
            if fname == tname:
497
471
 
498
472
    def StartStopProcess(self):
499
473
        """Run or abort the context of the current process if possible"""
500
 
        if self._prefs.get('autoclear'):
 
474
        if self.Preferences.get('autoclear', False):
501
475
            self._buffer.Clear()
502
476
 
 
477
        # Check Auto-save preferences
 
478
        if not self._busy:
 
479
            if self.Preferences.get('autosaveall', False):
 
480
                self.MainWindow.SaveAllBuffers()
 
481
            elif self.Preferences.get('autosave', False):
 
482
                self.MainWindow.SaveCurrentBuffer()
 
483
 
 
484
        # Start or stop the process
503
485
        self.SetProcessRunning(not self._busy)
504
486
        if self._busy:
505
487
            util.Log("[Launch][info] Starting process")
506
 
            handler = handlers.GetHandlerById(self._config['lang'])
 
488
            handler = handlers.GetHandlerById(self.State['lang'])
507
489
            cmd = self.FindWindowById(ID_EXECUTABLE).GetStringSelection()
508
 
            self._config['lcmd'] = cmd
 
490
            self.State['lcmd'] = cmd
509
491
            cmd = handler.GetCommand(cmd)
510
492
            args = self.FindWindowById(ID_ARGS).GetValue().split()
511
 
            self._config['largs'] = args
512
 
            self.Run(self._config['file'], cmd, args, self._config['lang'])
513
 
        else:
 
493
            self.State['largs'] = args
 
494
            self.Run(self.State['file'], cmd, args, self.State['lang'])
 
495
        elif self._worker:
514
496
            util.Log("[Launch][info] Aborting process")
515
497
            self._worker.Abort()
516
498
            self._worker = None
521
503
 
522
504
        """
523
505
        # Set currently selected file
524
 
        self._config['file'] = fname
 
506
        self.State['file'] = fname
525
507
        self._chFiles.SetStringSelection(os.path.split(fname)[1])
526
508
        self.GetControlBar().Layout()
527
509
 
530
512
        @param langid: syntax.synglob lang id
531
513
 
532
514
        """
533
 
        self._config['prelang'] = self._config['lang']
534
 
        self._config['lang'] = langid
 
515
        self.State['prelang'] = self.State['lang']
 
516
        self.State['lang'] = langid
535
517
 
536
518
    def SetProcessRunning(self, running=True):
537
519
        """Set the state of the window into either process running mode
539
521
        @keyword running: Is a process running or not
540
522
 
541
523
        """
542
 
        rbtn = self.FindWindowById(ID_RUN)
543
524
        self._busy = running
544
525
        if running:
545
 
            self._config['last'] = self._config['file']
546
 
            self._config['lastlang'] = self._config['lang']
547
 
            self._config['cfile'] = self._config['file']
548
 
            self._config['clang'] = self._config['lang']
 
526
            self.State['last'] = self.State['file']
 
527
            self.State['lastlang'] = self.State['lang']
 
528
            self.State['cfile'] = self.State['file']
 
529
            self.State['clang'] = self.State['lang']
549
530
            abort = wx.ArtProvider.GetBitmap(str(ed_glob.ID_STOP), wx.ART_MENU)
550
531
            if abort.IsNull() or not abort.IsOk():
551
532
                abort = wx.ArtProvider.GetBitmap(wx.ART_ERROR,
552
533
                                                 wx.ART_MENU, (16, 16))
553
 
            rbtn.SetBitmap(abort)
554
 
            rbtn.SetLabel(_("Abort"))
 
534
            self._run.SetBitmap(abort)
 
535
            self._run.SetLabel(_("Abort"))
555
536
        else:
556
537
            rbmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_BIN_FILE), wx.ART_MENU)
557
538
            if rbmp.IsNull() or not rbmp.IsOk():
558
539
                rbmp = None
559
 
            rbtn.SetBitmap(rbmp)
560
 
            rbtn.SetLabel(_("Run"))
 
540
            self._run.SetBitmap(rbmp)
 
541
            self._run.SetLabel(_("Run"))
561
542
            # If the buffer was changed while this was running we should
562
543
            # update to the new buffer now that it has stopped.
563
 
            self.SetFile(self._config['cfile'])
564
 
            self.SetLangId(self._config['clang'])
 
544
            self.SetFile(self.State['cfile'])
 
545
            self.SetLangId(self.State['clang'])
565
546
            self.RefreshControlBar()
566
547
 
567
548
        self.GetControlBar().Layout()
568
 
        rbtn.Refresh()
 
549
        self._run.Refresh()
569
550
 
570
551
    def SetupControlBar(self, ctrl):
571
552
        """Set the state of the controlbar based data found in the buffer
580
561
    def SetControlBarState(self, fname, lang_id):
581
562
        # Don't update the bars status if the buffer is busy
582
563
        if self._buffer.IsRunning():
583
 
            self._config['cfile'] = fname
584
 
            self._config['clang'] = lang_id
 
564
            self.State['cfile'] = fname
 
565
            self.State['clang'] = lang_id
585
566
        else:
586
 
            self.SetFile(fname)
587
 
            self.SetLangId(lang_id)
 
567
            if not self.Locked:
 
568
                self.SetFile(fname)
 
569
                self.SetLangId(lang_id)
588
570
 
589
 
            # Refresh the control bars view
590
 
            self.RefreshControlBar()
 
571
                # Refresh the control bars view
 
572
                self.RefreshControlBar()
591
573
 
592
574
    def UpdateBufferColors(self):
593
575
        """Update the buffers colors"""
594
576
        colors = dict()
595
577
        for color in ('defaultf', 'defaultb', 'errorf', 'errorb',
596
578
                      'infof', 'infob', 'warnf', 'warnb'):
597
 
            val = self._prefs.get(color, None)
 
579
            val = self.Preferences.get(color, None)
598
580
            if val is not None:
599
581
                colors[color] = wx.Colour(*val)
600
582
            else:
614
596
 
615
597
        """
616
598
        self._fnames = list()
617
 
        for txt_ctrl in self._mw.GetNotebook().GetTextControls():
 
599
        for txt_ctrl in self.MainWindow.GetNotebook().GetTextControls():
618
600
            if lang_id == txt_ctrl.GetLangId():
619
601
                self._fnames.append(txt_ctrl.GetFileName())
620
602
 
637
619
        eclib.ProcessBufferMixin.__init__(self)
638
620
 
639
621
        # Attributes
640
 
        self._mw = parent.GetMainWindow()
 
622
        self._mw = parent.MainWindow
641
623
        self._cfile = ''
642
 
        self._prefs = dict()
643
624
 
644
625
        # Setup
645
626
        font = Profile_Get('FONT1', 'font', wx.Font(11, wx.FONTFAMILY_MODERN,
646
627
                                                    wx.FONTSTYLE_NORMAL,
647
628
                                                    wx.FONTWEIGHT_NORMAL))
648
629
        self.SetFont(font)
 
630
        self.UpdateWrapMode()
 
631
 
 
632
    Preferences = property(lambda self: Profile_Get(handlers.CONFIG_KEY, default=dict()),
 
633
                           lambda self, prefs: Profile_Set(handlers.CONFIG_KEY, prefs))
649
634
 
650
635
    def ApplyStyles(self, start, txt):
651
636
        """Apply any desired output formatting to the text in
658
643
        style = handler.StyleText(self, start, txt)
659
644
 
660
645
        # Ring the bell if there was an error and option is enabled
661
 
        if style == handlers.STYLE_ERROR and self._prefs.get('errorbeep', False):
 
646
        if style == handlers.STYLE_ERROR and \
 
647
           self.Preferences.get('errorbeep', False):
662
648
            wx.Bell()
663
649
 
664
650
    def DoFilterInput(self, txt):
703
689
 
704
690
    def DoProcessExit(self, code=0):
705
691
        """Do all that is needed to be done after a process has exited"""
706
 
        self.AppendUpdate(">>> %s: %d%s" % (_("Exit Code"), code, os.linesep))
 
692
        # Peek in the queue to see the last line before the exit line
 
693
        queue = self.GetUpdateQueue()
 
694
        prepend_nl = True
 
695
        if len(queue):
 
696
            line = queue[-1]
 
697
        else:
 
698
            line = self.GetLine(self.GetLineCount() - 1)
 
699
        if line.endswith('\n') or line.endswith('\r'):
 
700
            prepend_nl = False
 
701
        final_line = u">>> %s: %d%s" % (_("Exit Code"), code, os.linesep)
 
702
        # Add an extra line feed if necessary to make sure the final line
 
703
        # is output on a new line.
 
704
        if prepend_nl:
 
705
            final_line = os.linesep + final_line
 
706
        self.AppendUpdate(final_line)
707
707
        self.Stop()
708
708
        self.GetParent().SetProcessRunning(False)
709
709
 
721
721
        handler = handlers.GetHandlerById(lang_id)
722
722
        return handler
723
723
 
724
 
    def SetPrefs(self, prefs):
725
 
        """Set the launch prefs
726
 
        @param prefs: dict
727
 
 
728
 
        """
729
 
        self._prefs = prefs
 
724
    def UpdateWrapMode(self):
 
725
        """Update the word wrapping mode"""
 
726
        mode = wx.stc.STC_WRAP_NONE
 
727
        if self.Preferences.get('wrapoutput', False):
 
728
            mode = wx.stc.STC_WRAP_WORD
 
729
        self.SetWrapMode(mode)
730
730
 
731
731
#-----------------------------------------------------------------------------#
732
732
def GetLangIdFromMW(mainw):