Source

mygrsync / mygrsyncframe.py

Full commit
  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
#Boa:Frame:mygrsync
# -*- coding: utf-8 -*-
import sys
import os
import subprocess
import time
import sqlite3
import locale
import re
import wx
import wx.stc

class G:
    str_encode = locale.getdefaultlocale()[1]
    _pg_RSYNC = 'rsync'
    _pg_GUIDIFF = 'bc2'

    if sys.platform == 'win32':
        if sys.version >= '2.6':
            nn = subprocess._subprocess
        else :
            nn = subprocess
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= nn.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = nn.SW_HIDE
        if sys.version >= '2.7':
            # win32 py>=2.7 subprocess._subprocess.CREATE_NEW_PROCESS_GROUP 512
            creationflags = subprocess._subprocess.CREATE_NEW_PROCESS_GROUP
        else:
            creationflags = 0
    else:
        startupinfo = None
        creationflags = 0

    db = sqlite3.connect(':memory:')
    cs = db.cursor()
    cs.execute('''create table KV(l varchar, r varchar) ''')
    cs.execute('''create table EXCLUDE(exclude varchar) ''')

    @classmethod
    def initfromfile(cls, fn='config.txt'):
        print '---------------- read config %s ----------------' % fn
        if fn == 'config.txt' and not os.path.exists(fn):
            open(fn, 'wb').write(open('config.template', 'rb').read())
        cls.cs.execute('''delete from KV''')
        cls.cs.execute('''delete from EXCLUDE''')
        data = open(fn, 'rb').read(1024**2)
        try:
            data = data.decode('utf-8').encode(G.str_encode)
            print 'config file encode is utf-8'
        except UnicodeDecodeError:
            print 'config file encode is %s' % G.str_encode
            pass
        for line in re.split('\n|\r', data):
            line = line.strip()
            if not line:
                continue
            if line[0] == '#':  # comment
                continue
            elif line[0] == ';':# add path and set program name
                kv = line[1:].split('=')
                if len(kv) == 2:
                    k, v = kv[0].strip().upper(), kv[1].strip()
                    if k and v:
                        if k == 'PATH':
                            if v not in os.environ['PATH']:
                                os.environ['PATH'] = v + os.pathsep + os.environ['PATH']
                                print ' add path %s' % v
                        else:
                            setattr(G, '_pg_%s' % k, v)
                            print ' set %s = %s' % (k, v)
                continue
            line = line.split('->')
            if len(line) != 2:
                continue
            l, r  = line[0].strip(), line[1].strip()
            cls.insert(l, r)
        print '---------------- read config file end ----------------'

    @classmethod
    def insert(cls, l, r):
        l = l.strip().replace('\\', '/')
        r = r.strip().replace('\\', '/')
        if not l or not r:
            print 'not enough lr: %s | %s' % (l, r)
            return
        if type(l) == type(''): l = l.decode(cls.str_encode)
        if type(r) == type(''): r = r.decode(cls.str_encode)
        if l[-2:] == '/*':
            if r[-2:] == '/*':  pass
            elif r[-1] == '/':  r += '*'
            else:               r += '/*'
            cls.cs.execute('''insert into EXCLUDE values (?)''', (l[:-2], ))
            cls.cs.execute('''select l, r from KV where l=? or l=? || '*' ''', (l[:-1], l[:-1]))
            val = cls.cs.fetchall()
            if val:
                print ' ---> has some dirname %d [%s],\t   ' % (
                    len(val), ', '.join([i[0].encode(cls.str_encode) for i in val])),
                cls.cs.execute('''delete from KV where l=? or l=? || '*' ''', (l[:-1], l[:-1]))
                print 'replace to "%s"' % l
            cls.cs.execute('''insert into KV values (?, ?)''', (l, r))
        else:
            if l[-1] != '/':    l += '/'
            if r[-1] != '/':    r += '/'
            cls.cs.execute('''select l, r from KV where l=? or l=? || '*' ''', (l, l))
            val = cls.cs.fetchall()
            if val:
                print ' ---> has some dirname %d [%s],\tNOT REPLACE TO "%s"' % (
                    len(val), ', '.join([i[0].encode(cls.str_encode) for i in val]), l)
            else:
                cls.cs.execute('''insert into KV values (?, ?)''', (l, r))

    @classmethod
    def getlr(cls, l='', r=''):
        if l:
            sql = '''select l,r from KV where upper(l)=upper(?) or upper(l)=upper(?) || '*'
                    order by length(l) desc'''
            x = l
        elif r:
            sql = '''select l,r from KV where upper(r)=upper(?) or upper(r)=upper(?) || '*'
                    order by length(l) desc'''
            x = r
        else:
            raise Exception('not l or r')
        x = x.strip()
        if not x:
            return '', ''
        if type(x) == type(''): x = x.decode(cls.str_encode)
        x = x.replace('\\', '/')

        value = None
        dn = ''
        while True:
            if x[-1] != '/': x += '/'
            cls.cs.execute(sql, (x, x))
            value = cls.cs.fetchone()
            if value:
                l, r = value[0], value[1]
                if l[-1:] == '*':
                    if dn:  l = '%s/%s/' % (l[:-2], dn)
                    else:   l = l[:-1]
                if r[-1:] == '*':
                    if dn:  r = '%s/%s/' % (r[:-2], dn)
                    else:   r = r[:-1]
                return l, r
            x, dn = os.path.split(x[:-1])
            if x == '' or dn == '':
                break
        return '', ''

    @classmethod
    def getexcludesfroml(cls, l):
        if not l: return []
        cls.cs.execute('''select exclude from EXCLUDE where upper(exclude) like '%s_%%' ''' % l.upper() )
        fs = cls.cs.fetchall()
        vs = []
        ln = len(l) - 1
        for v in fs:
            if v == l:
                continue
            vs.append(v[0][ln:])
        return vs

    @classmethod
    def getall(cls):
        cls.cs.execute('''select distinct l, r from KV order by upper(l)''')
        return cls.cs.fetchall()

    @classmethod
    def showall(cls):
        i = 0
        for k, v in cls.getall():
            i += 1
            print '%4d %s --> %s' % (i, k.encode(G.str_encode).ljust(38),
                                        v.encode(G.str_encode).ljust(38))
        cls.cs.execute('''select exclude from EXCLUDE''')
        i = 0
        for ex in cls.cs.fetchall():
            i += 1
            print '%4d exclude -> %s' % (i, ex[0])
        print '----------' * 6

    @staticmethod
    def cygpath(p, conv=True):
        '''
        p: path
        conv:: conv dospath to unixpath, True/False'''
        if not p:
            wx.MessageBox('Error path', 'Error', wx.ICON_ERROR)
            return ''
        if p.startswith('ssh'):
            return p
        if sys.platform == 'win32':
            if p[1] != ':':
                wx.MessageBox('Error Drive:/Path format', 'Error', wx.ICON_ERROR)
                return p
            if conv:
                p2 = '/cygdrive/%s/%s' % (p[0], p[3:].replace('\\', '/'))
                return p2
            else:
                return p
        else:
            if p[0] != '/':
                wx.MessageBox('Error /path/file format', 'Error', wx.ICON_ERROR)
                return p
            return p

    @staticmethod
    def runbc(l0=u'', r0=u''):
        if l0 and r0:
            l = l0.encode(G.str_encode)
            r = r0.encode(G.str_encode)
        elif l0 and not r0:
            l, r = G.getlr(l=l0)
            l = l.encode(G.str_encode)
            r = r.encode(G.str_encode)
        elif not l0 and r0:
            l, r = G.getlr(r=r0)
            l = l.encode(G.str_encode)
            r = r.encode(G.str_encode)
        else:
            print 'not dir, not run bc'
            return
        if not G.cygpath(l, False): return
        if not G.cygpath(r, False): return
        print '%s "%s" "%s"' % (G._pg_GUIDIFF, l, r)
        subprocess.Popen('%s "%s" "%s"' % (G._pg_GUIDIFF, l, r))

    @staticmethod
    def runsync(l, r, parent=None):
        lu = G.cygpath(l)
        ru = G.cygpath(r)
        if not lu or not ru:
            return
        import mygrsyncdlg
        mygrsyncdlg.G = G
        dlg = mygrsyncdlg.grsyncdlg(parent)
        dlg.SetTitle(dlg.GetTitle() + ' ' + l)
        dlg.txtSRC.SetValue(lu)
        dlg.txtDST.SetValue(ru)
        excludes = G.getexcludesfroml(l)
        excludes = ['"%s"' % i for i in excludes if i]
        dlg.txtExclude.SetValue('  '.join(excludes))
        dlg.Show()


def create(parent):
    return mygrsync(parent)

[wxID_MYGRSYNC, wxID_MYGRSYNCBTNCOMPARE, wxID_MYGRSYNCBTNEXIT, 
 wxID_MYGRSYNCBTNGETDIRS, wxID_MYGRSYNCBTNRSYNC, wxID_MYGRSYNCBTNSHOWLOG, 
 wxID_MYGRSYNCBTNSWITCH, wxID_MYGRSYNCCHK_TOPWINDOW, wxID_MYGRSYNCPANEL1, 
 wxID_MYGRSYNCSTATICTEXT1, wxID_MYGRSYNCSTATICTEXT2, wxID_MYGRSYNCTXTDST, 
 wxID_MYGRSYNCTXTSRC, 
] = [wx.NewId() for _init_ctrls in range(13)]

class mygrsync(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_MYGRSYNC, name=u'mygrsync', parent=prnt,
              pos=wx.Point(580, 0), size=wx.Size(341, 148),
              style=wx.DEFAULT_FRAME_STYLE, title=u'mygrsync')
        self.SetClientSize(wx.Size(325, 110))
        self.Bind(wx.EVT_CLOSE, self.OnMygrsyncClose)

        self.panel1 = wx.Panel(id=wxID_MYGRSYNCPANEL1, name='panel1',
              parent=self, pos=wx.Point(0, 0), size=wx.Size(325, 110),
              style=wx.TAB_TRAVERSAL)
        self.panel1.Bind(wx.EVT_LEFT_DCLICK, self.OnPanel1LeftDclick)
        self.panel1.Bind(wx.EVT_LEFT_UP, self.OnPanel1LeftUp)
        self.panel1.Bind(wx.EVT_LEFT_DOWN, self.OnPanel1LeftDown)

        self.staticText1 = wx.StaticText(id=wxID_MYGRSYNCSTATICTEXT1,
              label=u'SRC', name='staticText1', parent=self.panel1,
              pos=wx.Point(8, 8), size=wx.Size(21, 14), style=0)

        self.staticText2 = wx.StaticText(id=wxID_MYGRSYNCSTATICTEXT2,
              label=u'DST', name=u'staticText2', parent=self.panel1,
              pos=wx.Point(8, 32), size=wx.Size(23, 14), style=0)

        self.txtSRC = wx.TextCtrl(id=wxID_MYGRSYNCTXTSRC, name=u'txtSRC',
              parent=self.panel1, pos=wx.Point(32, 8), size=wx.Size(256, 22),
              style=0, value=u'')
        self.txtSRC.Bind(wx.EVT_TEXT, self.OnTxt_x, id=wxID_MYGRSYNCTXTSRC)

        self.txtDST = wx.TextCtrl(id=wxID_MYGRSYNCTXTDST, name=u'txtDST',
              parent=self.panel1, pos=wx.Point(32, 32), size=wx.Size(256, 22),
              style=0, value=u'')
        self.txtDST.Bind(wx.EVT_TEXT, self.OnTxt_x, id=wxID_MYGRSYNCTXTDST)

        self.btnSwitch = wx.Button(id=wxID_MYGRSYNCBTNSWITCH, label=u']',
              name=u'btnSwitch', parent=self.panel1, pos=wx.Point(288, 8),
              size=wx.Size(24, 48), style=0)
        self.btnSwitch.Bind(wx.EVT_BUTTON, self.OnBtnSwitchButton,
              id=wxID_MYGRSYNCBTNSWITCH)

        self.btnCompare = wx.Button(id=wxID_MYGRSYNCBTNCOMPARE,
              label=u'GUI diff', name=u'btnCompare', parent=self.panel1,
              pos=wx.Point(96, 64), size=wx.Size(56, 40), style=0)
        self.btnCompare.Enable(False)
        self.btnCompare.Bind(wx.EVT_BUTTON, self.OnBtnCompareButton,
              id=wxID_MYGRSYNCBTNCOMPARE)

        self.btnGetDirs = wx.Button(id=wxID_MYGRSYNCBTNGETDIRS,
              label=u'Look Copyed ', name=u'btnGetDirs', parent=self.panel1,
              pos=wx.Point(8, 64), size=wx.Size(88, 40), style=0)
        self.btnGetDirs.Bind(wx.EVT_BUTTON, self.OnBtnGetDirsButton,
              id=wxID_MYGRSYNCBTNGETDIRS)

        self.btnRsync = wx.Button(id=wxID_MYGRSYNCBTNRSYNC, label=u'Rsync',
              name=u'btnRsync', parent=self.panel1, pos=wx.Point(152, 64),
              size=wx.Size(56, 40), style=0)
        self.btnRsync.Bind(wx.EVT_BUTTON, self.OnBtnRsyncButton,
              id=wxID_MYGRSYNCBTNRSYNC)

        self.btnExit = wx.Button(id=wxID_MYGRSYNCBTNEXIT, label=u'EXIT',
              name=u'btnExit', parent=self.panel1, pos=wx.Point(216, 64),
              size=wx.Size(40, 40), style=0)
        self.btnExit.SetForegroundColour(wx.Colour(255, 0, 0))
        self.btnExit.Bind(wx.EVT_BUTTON, self.OnBtnExitButton,
              id=wxID_MYGRSYNCBTNEXIT)

        self.chk_topwindow = wx.CheckBox(id=wxID_MYGRSYNCCHK_TOPWINDOW,
              label=u'Top', name=u'chk_topwindow', parent=self.panel1,
              pos=wx.Point(272, 56), size=wx.Size(48, 24), style=0)
        self.chk_topwindow.SetValue(False)
        self.chk_topwindow.Bind(wx.EVT_CHECKBOX, self.OnChk_topwindowCheckbox,
              id=wxID_MYGRSYNCCHK_TOPWINDOW)

        self.btnShowLog = wx.Button(id=wxID_MYGRSYNCBTNSHOWLOG, label=u'>>',
              name=u'btnShowLog', parent=self.panel1, pos=wx.Point(272, 80),
              size=wx.Size(48, 24), style=0)
        self.btnShowLog.Bind(wx.EVT_BUTTON, self.OnBtnShowLogButton,
              id=wxID_MYGRSYNCBTNSHOWLOG)

    def __init__(self, parent):
        self._init_ctrls(parent)
        di = os.path.dirname(os.path.abspath(__file__))
        if os.path.isfile(di):
            di = os.path.dirname(di)
        if os.path.isdir(di):
            os.chdir(di)

        self.initctls()
        self.initcfg()

    def initctls(self):
        self.leftmd = False
        ff = wx.Font(9, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Courier New')
        self.txtSRC.SetFont(ff)
        self.txtDST.SetFont(ff)
        self.btnCompare.Disable()
        self.btnRsync.Disable()
        self.panel1.Bind(wx.EVT_MOTION, self.OnPanelMotion)
        self.settopwindow()
        self.initlogwin(ff)

    def initlogwin(self, ff):
        dc = wx.ScreenDC()
        sz = dc.GetSize()
        dc.Destroy()
        self._logdlg = wx.Dialog(self, title=u"mygrsync log", size=wx.Size(440,640),
                                 pos = (sz.x-440, 0),
                                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self._logstc = wx.stc.StyledTextCtrl(self._logdlg)
        self._logstc.StyleSetFont(wx.stc.STC_STYLE_DEFAULT, ff)
        self._logstc.SetMarginType(1, wx.stc.STC_MARGIN_NUMBER)
        self._logstc.SetMarginWidth(1, 24)
        self._logstc.SetSize(self._logdlg.GetClientSize())
        self._logstc.AppendText('%s\n%s\n\n' % (
            time.strftime('  %Y-%m-%d %H:%M:%S\n'), os.getcwdu()))
        self._logstc.EmptyUndoBuffer()
        if '--stdout' not in sys.argv:
            self._stdout, self._stderr = sys.stdout, sys.stderr
            sys.stdout, sys.stderr = self, self

    def OnMygrsyncClose(self, event):
        event.Skip()
        if hasattr(self, '_stdout'):
            sys.stdout, sys.stderr = self._stdout, self._stderr
            print 'reset sys.stdout, mainframe close'

    def write(self, txt):
        if type(txt) == type(u''):
            pass
        elif type(txt) == type(''):
            txt = txt.decode(G.str_encode, 'replace')
        else:
            txt = str(txt).decode(G.str_encode, 'replace')
        self._logstc.AppendText(txt)
        self._logstc.GotoLine(self._logstc.GetLineCount())

    def initcfg(self):
        G.initfromfile()
        G.showall()

    def OnBtnSwitchButton(self, event):
        t1 = self.txtSRC.GetValue()
        t2 = self.txtDST.GetValue()
        self.txtSRC.SetValue(t2)
        self.txtDST.SetValue(t1)
        self.initcfg()

    def OnBtnGetDirsButton(self, event):
        fn = fn1 = fn2 = ''
        self.txtSRC.SetValue('')
        self.txtDST.SetValue('')
        clip = wx.TheClipboard
        if clip.Open():
            cf = wx.FileDataObject()
            if clip.GetData(cf):
                fs = cf.GetFilenames()
                if fs:
                    if os.path.isfile(fs[0]):
                        fn = os.path.dirname(fs[0]).replace('\\', '/')
                    else:
                        fn = fs[0].replace('\\', '/')
            clip.Close()
        if fn:
            fn1, fn2 = G.getlr(l=fn)
            if not fn2:
                fn1, fn2 = G.getlr(r=fn)
            self.txtSRC.SetValue(fn)
        else:
            self.txtSRC.SetValue('')
        if fn1 and fn2:
            self.txtSRC.SetValue(fn1)
            self.txtDST.SetValue(fn2)
            self.btnCompare.Enable()
            self.btnRsync.Enable()
            print ' parse file: %s ( %s -> %s )' % (fn.encode(G.str_encode),
                fn1.encode(G.str_encode), fn2.encode(G.str_encode))
        else:
            self.btnCompare.Disable()
            self.btnRsync.Disable()
            print ' CAN NOT parse: %s ( %s -> %s )' % (fn.encode(G.str_encode),
                fn1.encode(G.str_encode), fn2.encode(G.str_encode))

    def OnBtnCompareButton(self, event):
        event.Skip()
        l = self.txtSRC.GetValue()
        r = self.txtDST.GetValue()
        G.runbc(l, r)

    def OnBtnRsyncButton(self, event):
        event.Skip()
        l = self.txtSRC.GetValue()
        r = self.txtDST.GetValue()
        G.runsync(l, r)

    def OnBtnExitButton(self, event):
        event.Skip()
        self.Close()

    def OnTxt_x(self, event):
        event.Skip()
        self.btnCompare.Enable()
        self.btnRsync.Enable()

    def OnChk_topwindowCheckbox(self, event):
        self.settopwindow()

    def OnPanel1LeftDclick(self, event):
        self.settopwindow()

    def settopwindow(self):
        if self.GetWindowStyle() != wx.STAY_ON_TOP:
            if not hasattr(self, '_winstyle'):
                self._winstyle = self.GetWindowStyle()
            self.SetWindowStyle(wx.STAY_ON_TOP)
            if sys.platform == 'win32':
                sz = self.GetSize()
                self.SetSize(wx.Size(sz.x, sz.y - self.btnCompare.GetSize().y))
            self.chk_topwindow.SetValue(True)
        else:
            self.SetWindowStyle(self._winstyle)
            if sys.platform == 'win32':
                sz = self.GetSize()
                self.SetSize(wx.Size(sz.x, sz.y + self.btnCompare.GetSize().y))
            self.chk_topwindow.SetValue(False)

    def OnPanel1LeftDown(self, event):
        event.Skip()
        self.panel1.CaptureMouse()
        mouse=wx.GetMousePosition()
        frame=self.GetPosition()
        self.delta=wx.Point(mouse.x-frame.x,mouse.y-frame.y)
        self.leftmd = True

    def OnPanel1LeftUp(self, event):
        event.Skip()
        if self.panel1.HasCapture():
            self.panel1.ReleaseMouse()
        self.leftmd = False

    def OnPanelMotion(self, event):
        if event.Dragging() and self.leftmd:
            mouse=wx.GetMousePosition()
            self.Move((mouse.x-self.delta.x,\
                       mouse.y-self.delta.y))

    def OnBtnShowLogButton(self, event):
        event.Skip()
        if self._logdlg.IsShown():
            self._logdlg.Hide()
        else:
            self._logdlg.Show()