File: wb_app.py

package info (click to toggle)
svn-workbench 1.5.0-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 2,400 kB
  • ctags: 1,585
  • sloc: python: 12,163; sh: 74; makefile: 46; ansic: 9
file content (472 lines) | stat: -rw-r--r-- 16,258 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
'''
 ====================================================================
 Copyright (c) 2003-2006 Barry A Scott.  All rights reserved.

 This software is licensed as described in the file LICENSE.txt,
 which you should have received as part of this distribution.

 ====================================================================

    wb_app.py

'''
import sys
import os
import types
import logging
import tempfile
import threading

import wx
import wx.lib
import wx.lib.newevent

import wb_frame
import wb_preferences
import wb_platform_specific
import wb_exceptions
import wb_diff_frame
import wb_show_diff_frame
import wb_dialogs
import wb_background_thread
import wb_shell_commands

wx.InitAllImageHandlers()

AppCallBackEvent, EVT_APP_CALLBACK = wx.lib.newevent.NewEvent()

class WbApp(wx.App):
    def __init__( self, startup_dir, args ):
        self.args = args
        self.app_name = os.path.basename( args[0] )
        self.app_dir = os.path.dirname( args[0] )
        self.main_thread = threading.currentThread()

        self.progress_format = None
        self.progress_values = {}

        wb_platform_specific.setupPlatform()

        # --project <dir> automatically creates a project entry for <dir>
        # if <dir> is a subversion working copy and no project entry exists for it.
        self.auto_project_dir = None
        if '--project' in args:
            project_arg_index = args.index( '--project' )
            if project_arg_index < len( args ) - 1:
               self.auto_project_dir = os.path.abspath( os.path.join( startup_dir, args[ project_arg_index+1 ] ) )

        # Debug settings

        # don't redirect IO into the log window
        self.__debug_noredirect = '--noredirect' in args

        # enable debug messages
        self.__debug = '--debug' in args
        self.__trace = '--trace' in args

        self.__last_client_error = []

        self.setupLogging()

        self.prefs = wb_preferences.Preferences( self )

        self.lock_ui = 0
        self.need_activate_app_action = False

        self.frame = None
        self.all_diff_frames = []
        self.all_temp_files = []

        self.__paste_data = None

        self.background_thread = wb_background_thread.BackgroundThread()
        self.background_thread.start()

        wx.App.__init__( self, 0 )

        try_wrapper = wb_exceptions.TryWrapperFactory( self.log )

        wx.EVT_ACTIVATE_APP( self, try_wrapper( self.OnActivateApp ) )
        EVT_APP_CALLBACK( self, try_wrapper( self.OnAppCallBack ) )

    def isStdIoRedirect( self ):
        return not self.__debug_noredirect

    def eventWrapper( self, function ):
        return EventScheduling( self, function )

    def isMainThread( self ):
        'return true if the caller is running on the main thread'
        return self.main_thread is threading.currentThread()

    def setupLogging( self ):
        self.log = logging.getLogger( 'WorkBench' )
        self.trace = logging.getLogger( 'WorkBench.Trace' )

        if self.__debug:
            self.log.setLevel( logging.DEBUG )
        else:
            self.log.setLevel( logging.INFO )

        if self.__trace:
            self.trace.setLevel( logging.INFO )
        else:
            self.trace.setLevel( logging.CRITICAL )

        log_filename = wb_platform_specific.getLogFilename()
        # keep 10 logs of 100K each
        handler = RotatingFileHandler( log_filename, 'a', 100*1024, 10 )
        formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s' )
        handler.setFormatter( formatter )
        self.log.addHandler( handler )

        if not self.isStdIoRedirect():
            handler = StdoutLogHandler()
            formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s' )
            handler.setFormatter( formatter )
            self.log.addHandler( handler )

            handler = StdoutLogHandler()
            formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s' )
            handler.setFormatter( formatter )
            self.trace.addHandler( handler )

        self.log.info( 'Work Bench starting' )

        self.log.debug( 'debug enabled' )
        self.trace.info( 'trace enabled' )

    def log_client_error( self, e, title='Error' ):
        # must run on the main thread
        if not self.isMainThread():
            self.foregroundProcess( self.log_client_error, (e, title) )
            return

        self.__last_client_error = []
        for message, _ in e.args[1]:
            self.__last_client_error.append( message )
            self.log.error( message )

        wx.MessageBox( '\n'.join( self.__last_client_error ), title, style=wx.OK|wx.ICON_ERROR );

    def log_error( self, e, title='Error' ):
        # must run on the main thread
        if not self.isMainThread():
            self.foregroundProcess( self.log_error, (e, title) )
            return

        message = str( e )
        self.log.error( message )

        wx.MessageBox( message, title, style=wx.OK|wx.ICON_ERROR );

    def refreshFrame( self ):
        self.frame.refreshFrame()

    def expandSelectedTreeNode( self ):
        self.frame.expandSelectedTreeNode()

    def selectTreeNodeInParent( self, filename ):
        self.frame.selectTreeNodeInParent( filename )

    def selectTreeNode( self, filename ):
        self.frame.selectTreeNode( filename )

    def setAction( self, msg ):
        self.frame.setAction( msg )

    def setProgress( self, fmt, total ):
        self.progress_format = fmt
        self.progress_values['total'] = total
        self.progress_values['count'] = 0
        self.progress_values['percent'] = 0
        self.frame.setProgress( self.progress_format % self.progress_values )

    def incProgress( self ):
        if self.progress_format is None:
            return
        self.progress_values['count'] += 1
        if self.progress_values['total'] > 0:
            self.progress_values['percent'] = self.progress_values['count']*100/self.progress_values['total']
        self.frame.setProgress( self.progress_format % self.progress_values )

    def getProgressValue( self, name ):
        return self.progress_values[ name ]

    def clearProgress( self ):
        self.progress_format = None
        self.frame.setProgress( '' )

    def setPasteData( self, data ):
        self.__paste_data = data

    def clearPasteData( self ):
        self.__paste_data = None

    def hasPasteData( self ):
        return self.__paste_data is not None

    def getPasteData( self ):
        return self.__paste_data

    def DiffDone( self, diff_frame ):
        self.all_diff_frames.remove( diff_frame )

    def confirmAction( self, title, all_filenames ):
        dialog = wb_dialogs.ConfirmAction( self.frame, title, all_filenames )
        result = dialog.ShowModal()
        return result == wx.ID_OK

    def confirmForceAction( self, title, all_filenames ):
        dialog = wb_dialogs.ConfirmAction( self.frame, title, all_filenames, force_field=True )
        result = dialog.ShowModal()
        return result == wx.ID_OK, dialog.getForce()

    def getLogMessage( self, title, all_filenames ):
        dialog = wb_dialogs.LogMessage( self.frame, title, all_filenames,
                                        wb_platform_specific.getLastCheckinMessageFilename() )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            return dialog.getLogMessage()
        return None

    def getLockMessage( self, title, all_filenames ):
        dialog = wb_dialogs.LogMessage( self.frame, title, all_filenames,
                                        wb_platform_specific.getLastLockMessageFilename(), force_field=True )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            return dialog.getLogMessage(), dialog.getForce()
        return None, False

    def addFile( self, title, name, force ):
        dialog = wb_dialogs.AddDialog( self.frame, title, name, force )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            return dialog.getForce()
        return None

    def renameFile( self, title, old_name, force=None ):
        dialog = wb_dialogs.RenameFile( self.frame, title, old_name, force )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            return dialog.getNewFilename(), dialog.getForce()
        return None, None

    def getCredentials( self, realm, username, may_save ):
        # signature allows use a pysvn callback
        dialog = wb_dialogs.GetCredentials( self.frame, realm, username, may_save )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            return (True, dialog.getUsername().encode('UTF-8'),
                dialog.getPassword().encode('UTF-8'), dialog.getSaveCredentials())
        else:
            return False, '', '', False

    def getServerTrust( self, realm, info_list, may_save ):
        # signature allows use a pysvn callback
        dialog = wb_dialogs.GetServerTrust( self.frame, realm, info_list, may_save )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            # Trust, save
            return True, dialog.getSaveTrust()
        else:
            # don't trust, don't save
            return False, False

    def getFilename( self, title, border_title ):
        dialog = wb_dialogs.GetFilename( self.frame, title, border_title )
        result = dialog.ShowModal()
        if result == wx.ID_OK:
            return True, dialog.getNewFilename()
        else:
            return False, ''

    def savePreferences( self ):
        self.prefs.writePreferences()

    def exitAppNow( self ):
        if self.lock_ui > 0:
            # return False to veto a close
            return False

        # o.k. to exit
        for temp_file in self.all_temp_files:
            self.log.info( 'Removing "%s".' % temp_file )
            try:
                os.remove( temp_file )
            except OSError:
                pass

        self.frame.savePreferences()
        self.prefs.writePreferences()
        self.frame = None

        return True

    def OnInit(self):
        self.frame = wb_frame.WbFrame( self )
        self.frame.Show( True )
        self.SetTopWindow( self.frame )

        self.foregroundProcess( self.frame.tree_panel.initFrame, () )
        return True

    def OnActivateApp( self, event ):
        if self.frame is None:
            # too early or too late
            return

        if self.lock_ui == 0:
            self.frame.OnActivateApp( event.GetActive() )
        else:
            if event.GetActive():
                self.need_activate_app_action = True

    def backgroundProcess( self, function, args ):
        self.background_thread.addWork( AppBackgroundFunction( self, function, args ) )

    def foregroundProcess( self, function, args ):
        wx.PostEvent( self, AppCallBackEvent( callback=function, args=args ) )

    def OnAppCallBack( self, event ):
        try:
            event.callback( *event.args )
        except:
            self.log.exception( 'OnAppCallBack<%s.%s>\n' %
                (event.callback.__module__, event.callback.__name__ ) )

class AppBackgroundFunction:
    def __init__( self, app, function, args ):
        self.app = app
        self.function = function
        self.args = args

    def __call__( self ):
        self.app.trace.info( 'AppBackgroundFunction<%s.%s>.__call__()' %
                (self.function.__module__, self.function.__name__) )
        try:
            self.function( *self.args )
        except:
            self.app.log.exception( 'AppBackgroundFunction<%s.%s>\n' %
                (self.function.__module__, self.function.__name__) )

class EventScheduling:
    def __init__( self, app, function ):
        self.app = app
        self.function = function

    def __call__( self, *args, **kwds ):
        self.app.trace.info( 'EventScheduling<%s.%s>.__call__()' %
                (self.function.__module__, self.function.__name__) )
        try:
            # call the function
            result = self.function( *args, **kwds )

            # did the function run or make a generator?
            if type(result) != types.GeneratorType:
                # it ran - we are all done
                return

            # step the generator
            stepGenerator( self.app, result )
        except:
            self.app.log.exception( 'EventScheduling<%s.%s>\n' %
                (self.function.__module__, self.function.__name__ ) )

def stepGenerator( app, generator ):
    app.trace.info( 'stepGenerator<%r>() next_fn=%r' % (generator, generator.next) )

    # result tells where to schedule the generator to next
    try:
        where_to_go_next = generator.next()
        app.trace.info( 'stepGenerator<%r>() next=>%r' % (generator, where_to_go_next) )

    except StopIteration:
        # no problem all done
        return

    # will be one of app.foregroundProcess or app.backgroundProcess
    where_to_go_next( stepGenerator, (app, generator) )

#--------------------------------------------------------------------------------
#
#    RotatingFileHandler - based on python lib class
#
#--------------------------------------------------------------------------------
class RotatingFileHandler(logging.FileHandler):
    def __init__(self, filename, mode="a", maxBytes=0, backupCount=0):
        """
        Open the specified file and use it as the stream for logging.

        By default, the file grows indefinitely. You can specify particular
        values of maxBytes and backupCount to allow the file to rollover at
        a predetermined size.

        Rollover occurs whenever the current log file is nearly maxBytes in
        length. If backupCount is >= 1, the system will successively create
        new files with the same pathname as the base file, but with extensions
        ".1", ".2" etc. appended to it. For example, with a backupCount of 5
        and a base file name of "app.log", you would get "app.log",
        "app.log.1", "app.log.2", ... through to "app.log.5". The file being
        written to is always "app.log" - when it gets filled up, it is closed
        and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc.
        exist, then they are renamed to "app.log.2", "app.log.3" etc.
        respectively.

        If maxBytes is zero, rollover never occurs.
        """
        logging.FileHandler.__init__(self, filename, mode)
        self.maxBytes = maxBytes
        self.backupCount = backupCount
        if maxBytes > 0:
            self.mode = "a"

    def doRollover(self):
        """
        Do a rollover, as described in __init__().
        """

        self.stream.close()
        if self.backupCount > 0:
            prefix, suffix = os.path.splitext( self.baseFilename )
            for i in range(self.backupCount - 1, 0, -1):
                sfn = "%s.%d%s" % (prefix, i, suffix)
                dfn = "%s.%d%s" % (prefix, i+1, suffix)
                if os.path.exists(sfn):
                    #print "%s -> %s" % (sfn, dfn)
                    if os.path.exists(dfn):
                        os.remove(dfn)
                    os.rename(sfn, dfn)
            dfn = self.baseFilename + ".1"
            if os.path.exists(dfn):
                os.remove(dfn)
            os.rename(self.baseFilename, dfn)
            #print "%s -> %s" % (self.baseFilename, dfn)
        self.stream = open(self.baseFilename, "w")

    def emit(self, record):
        """
        Emit a record.

        Output the record to the file, catering for rollover as described
        in setRollover().
        """
        if self.maxBytes > 0:                   # are we rolling over?
            msg = "%s\n" % self.format(record)
            self.stream.seek(0, 2)  #due to non-posix-compliant Windows feature
            if self.stream.tell() + len(msg) >= self.maxBytes:
                self.doRollover()
        logging.FileHandler.emit(self, record)

class StdoutLogHandler(logging.Handler):
    def __init__( self ):
        logging.Handler.__init__( self )

    def emit( self, record ):
        try:
            msg = self.format(record) + '\n'

            sys.__stdout__.write( msg )

        except:
            self.handleError(record)