Commits

windwiny  committed aabbf6b

reorg

  • Participants
  • Parent commits 17be956

Comments (0)

Files changed (4)

File grsync.py

-# -*- coding: utf-8 -*-
-import sys
-import os
-import sqlite3
-import locale
-import wx
-
-class G:
-    str_encode = locale.getdefaultlocale()[1]
-    db = sqlite3.connect(':memory:')
-    cs = db.cursor()
-    cs.execute('''create table KV(l, r) ''')
-    
-    @classmethod
-    def insert(cls, l, r):
-        if type(l) == type(''):
-            l = l.decode(cls.str_encode)
-        if type(r) == type(''):
-            r = r.decode(cls.str_encode)
-        cls.cs.execute('''insert into KV values (?, ?)''', (l, r))
-
-    @classmethod
-    def getL(cls, l):
-        if type(l) == type(''):
-            l = l.decode(cls.str_encode)
-        cls.cs.execute('''select r from KV where upper(l)=upper(?)''', (l, ))
-        return cls.cls.fetch()
-
-    @classmethod
-    def getR(cls, r):
-        if type(r) == type(''):
-            r = r.decode(cls.str_encode)
-        cls.cs.execute('''select l from KV where upper(r)=upper(?)''', (r, ))
-        return cls.cls.fetchone()
-
-def cygpath(p):
-    assert p[1] == ':'
-    p2 = '/cygdrive/%s%s' % (p[0], p[2:].replace('\\', '/'))
-    return p2
-
-def runbc(l='', r=''):
-    global L, R
-    if l:
-        r = G.getL(l).encode(G.str_encode)
-    elif r:
-        l = G.getR(r).encode(G.str_encode)
-    else:
-        return
-    os.environ['PATH']= r"d:\Program Files\Beyond Compare 2;" + os.environ['PATH']
-    os.popen('bc2 "%s" "%s"' % (l, r))
-    
-def runsync(l, r):
-    os.environ['PATH']= r"f:\cygwin\bin;" + os.environ['PATH']
-    
-    lu = cygpath(l)
-    ru = cygpath(r)
-    import mygrsyncdlg
-    dlg = mygrsyncdlg.grsyncdlg(None)
-    dlg.txtSRC.SetValue(lu.decode('gbk'))
-    dlg.txtDST.SetValue(ru.decode('gbk'))
-    dlg.Show()
-
-    
-def init():
-    global L, R
-    f = open('config.txt', 'r')
-    for line in f:
-        line = line.strip().upper()
-        if not line:
-            continue
-        if line[0] == '#':
-            continue
-        line = line.split('->')
-        if len(line) != 2:
-            continue
-        l, r  = line[0].strip(), line[1].strip()
-        L[l] = r
-        R[r] = l
-
-def print1():
-    global L, R
-    for k, v in L.items():
-        print k, '-->', v
-
-
-[wxID_FRAME2, wxID_FRAME2BTNCOMPARE, wxID_FRAME2PANEL1, 
- wxID_FRAME2STATICTEXT1, wxID_FRAME2STATICTEXT2, wxID_FRAME2TEXTCTRL1, 
- wxID_FRAME2TEXTCTRL2, 
-] = [wx.NewId() for _init_ctrls in range(7)]
-
-class Frame2(wx.Frame):
-    def _init_ctrls(self, prnt):
-        # generated method, don't edit
-        wx.Frame.__init__(self, id=wxID_FRAME2, name='', parent=prnt,
-              pos=wx.Point(537, 252), size=wx.Size(317, 148),
-              style=wx.DEFAULT_FRAME_STYLE, title='Frame2')
-        self.SetClientSize(wx.Size(301, 110))
-
-        self.panel1 = wx.Panel(id=wxID_FRAME2PANEL1, name='panel1', parent=self,
-              pos=wx.Point(0, 0), size=wx.Size(301, 110),
-              style=wx.TAB_TRAVERSAL)
-
-        self.staticText1 = wx.StaticText(id=wxID_FRAME2STATICTEXT1,
-              label=u'Left', name='staticText1', parent=self.panel1,
-              pos=wx.Point(16, 8), size=wx.Size(22, 14), style=0)
-
-        self.staticText2 = wx.StaticText(id=wxID_FRAME2STATICTEXT2,
-              label=u'Right', name=u'staticText2', parent=self.panel1,
-              pos=wx.Point(8, 32), size=wx.Size(28, 14), style=0)
-
-        self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL1, name='textCtrl1',
-              parent=self.panel1, pos=wx.Point(40, 8), size=wx.Size(256, 22),
-              style=0, value=u'')
-
-        self.textCtrl2 = wx.TextCtrl(id=wxID_FRAME2TEXTCTRL2, name='textCtrl2',
-              parent=self.panel1, pos=wx.Point(40, 32), size=wx.Size(256, 22),
-              style=0, value=u'')
-
-        self.btnCompare = wx.Button(id=wxID_FRAME2BTNCOMPARE, label=u'Compare',
-              name=u'btnCompare', parent=self.panel1, pos=wx.Point(72, 64),
-              size=wx.Size(184, 40), style=0)
-        self.btnCompare.Bind(wx.EVT_BUTTON, self.OnBtnCompareButton,
-              id=wxID_FRAME2BTNCOMPARE)
-
-    def __init__(self, parent):
-        self._init_ctrls(parent)
-        init()
-
-    def OnBtnCompareButton(self, event):
-        event.Skip()
-        print1()
-        l = self.textCtrl1.GetValue().encode('gbk').upper()
-        r = self.textCtrl2.GetValue().encode('gbk').upper()
-        runsync(l, r)
-        runbc(l)
-
-
-class BoaApp(wx.App):
-    def OnInit(self):
-        self.main = Frame2(None)
-        self.main.Show()
-        self.SetTopWindow(self.main)
-        return True
-
-def main():
-    application = BoaApp(0)
-    application.MainLoop()
-
-if __name__ == '__main__':
-    main()

File grsyncdlg.py

-# coding: utf-8
-
-import wx
-
-class MyFrame(wx.Frame):
-    def __init__(self):
-        wx.Frame.__init__(self,None,-1,"my grsync")
-        ff = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False,  u'Courier New' )
-        self.SetFont(ff)
-        box1 = wx.BoxSizer(wx.VERTICAL)
-        panel1 = wx.Panel(self)
-        
-        syn= open('rsyncsyntax.g').readlines()
-        for line0 in syn:
-            line = line0.strip()
-            if not line or line[0] == '#': continue
-            if line.startswith('--'):
-                li = line.split()
-                pname = li[0]
-                pname1 = ''
-                pvalue = ' '.join(li[1:])
-            if line.startswith('-'):
-                li = line.replace(',', ' ', 1)
-                li = li.split()
-                if len(li) < 3 or not li[1].startswith('--'):
-                    pname = li[0]
-                    pname1 = ''
-                    pvalue = ' '.join(li[1:])
-                else:
-                    pname, pname1= li[0:2]
-                    pvalue = ' '.join(li[2:])
-            else:
-                    raise Exception("syntax file error! %s" % line0)
-            #print '%38s %38s %s '  % (pname, pname1, pvalue)
-            if '=' in pname1:
-                assert '=' not in pname
-                pname, pname1 = pname, ''
-            if '=' in pname:
-                boxx = wx.BoxSizer()
-                ctl = wx.StaticText(panel1, label=line0)
-                boxx.Add(ctl )
-                ctl = wx.TextCtrl(panel1)
-                boxx.Add(ctl )
-                box1.AddSizer(boxx)
-            else:
-                ctl = wx.CheckBox(panel1, label=line0)
-                box1.Add(ctl )
-        panel1.SetSizer(box1)
-def main():
-    app = wx.App(0)
-    frm = MyFrame()
-    app.SetTopWindow(frm)
-    frm.Show()
-    app.MainLoop()
-
-if __name__ =='__main__':
-    main()
-    

File rsyncsyntax.g

- 
-# rsync  version 3.0.8  protocol version 30
-  
-# Usage: rsync [OPTION]... SRC [SRC]... DEST
-#   or   rsync [OPTION]... SRC [SRC]... [USER@]HOST:DEST
-#   or   rsync [OPTION]... SRC [SRC]... [USER@]HOST::DEST
-#   or   rsync [OPTION]... SRC [SRC]... rsync://[USER@]HOST[:PORT]/DEST
-#   or   rsync [OPTION]... [USER@]HOST:SRC [DEST]
-#   or   rsync [OPTION]... [USER@]HOST::SRC [DEST]
-#   or   rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]
-# The ':' usages connect via remote shell, while '::' & 'rsync://' usages connect
-# to an rsync daemon, and require SRC or DEST to start with a module name.
-  
- -n, --dry-run               perform a trial run with no changes made
- -v, --verbose               increase verbosity
-
- -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
-
- -r, --recursive             recurse into directories
- -l, --links                 copy symlinks as symlinks
- -p, --perms                 preserve permissions
- -t, --times                 preserve modification times
- -g, --group                 preserve group
- -o, --owner                 preserve owner (super-user only)
- -D                          same as --devices --specials
-     --devices               preserve device files (super-user only)
-     --specials              preserve special files
- -A, --acls                  preserve ACLs (implies --perms)
- -X, --xattrs                preserve extended attributes
-     --numeric-ids           don't map uid/gid values by user/group name
-
-
-     --del                   an alias for --delete-during
-     --delete                delete extraneous files from destination dirs
-     --delete-before         receiver deletes before transfer, not during
-     --delete-during         receiver deletes during transfer (default)
-     --delete-delay          find deletions during, delete after
-     --delete-after          receiver deletes after transfer, not during
-     --delete-excluded       also delete excluded files from destination dirs
-
-
-     --ignore-existing       skip updating files that already exist on receiver
-     --existing              skip creating new files on receiver
- -u, --update                skip files that are newer on the receiver
- -x, --one-file-system       don't cross filesystem boundaries
- -P                          same as --partial --progress
-     --partial               keep partially transferred files
-     --progress              show progress during transfer
-     --size-only             skip files that match in size
-     --modify-window=NUM     compare mod-times with reduced accuracy
-
- -H, --hard-links            preserve hard links
-
- -c, --checksum              skip based on checksum, not mod-time & size
-
- -b, --backup                make backups (see --suffix & --backup-dir)
-     --backup-dir=DIR        make backups into hierarchy based in DIR
-     --suffix=SUFFIX         set backup suffix (default ~ w/o --backup-dir)
-
- -q, --quiet                 suppress non-error messages
-     --no-motd               suppress daemon-mode MOTD (see manpage caveat)
-     --no-OPTION             turn off an implied OPTION (e.g. --no-D)
- -R, --relative              use relative path names
-     --no-implied-dirs       don't send implied dirs with --relative
-     --inplace               update destination files in-place (SEE MAN PAGE)
-     --append                append data onto shorter files
-     --append-verify         like --append, but with old data in file checksum
- -d, --dirs                  transfer directories without recursing
- -L, --copy-links            transform symlink into referent file/dir
-     --copy-unsafe-links     only "unsafe" symlinks are transformed
-     --safe-links            ignore symlinks that point outside the source tree
- -k, --copy-dirlinks         transform symlink to a dir into referent dir
- -K, --keep-dirlinks         treat symlinked dir on receiver as dir
- -E, --executability         preserve the file's executability
-     --chmod=CHMOD           affect file and/or directory permissions
- -O, --omit-dir-times        omit directories from --times
-     --super                 receiver attempts super-user activities
-     --fake-super            store/recover privileged attrs using xattrs
- -S, --sparse                handle sparse files efficiently
- -W, --whole-file            copy files whole (without delta-xfer algorithm)
- -B, --block-size=SIZE       force a fixed checksum block-size
- -e, --rsh=COMMAND           specify the remote shell to use
-     --rsync-path=PROGRAM    specify the rsync to run on the remote machine
-     --remove-source-files   sender removes synchronized files (non-dirs)
-     --ignore-errors         delete even if there are I/O errors
-     --force                 force deletion of directories even if not empty
-     --max-delete=NUM        don't delete more than NUM files
-     --max-size=SIZE         don't transfer any file larger than SIZE
-     --min-size=SIZE         don't transfer any file smaller than SIZE
-     --partial-dir=DIR       put a partially transferred file into DIR
-     --delay-updates         put all updated files into place at transfer's end
- -m, --prune-empty-dirs      prune empty directory chains from the file-list
-     --timeout=SECONDS       set I/O timeout in seconds
-     --contimeout=SECONDS    set daemon connection timeout in seconds
- -I, --ignore-times          don't skip files that match in size and mod-time
- -T, --temp-dir=DIR          create temporary files in directory DIR
- -y, --fuzzy                 find similar file for basis if no dest file
-     --compare-dest=DIR      also compare destination files relative to DIR
-     --copy-dest=DIR         ... and include copies of unchanged files
-     --link-dest=DIR         hardlink to files in DIR when unchanged
- -z, --compress              compress file data during the transfer
-     --compress-level=NUM    explicitly set compression level
-     --skip-compress=LIST    skip compressing files with a suffix in LIST
- -C, --cvs-exclude           auto-ignore files the same way CVS does
- -f, --filter=RULE           add a file-filtering RULE
- -F                          same as --filter='dir-merge /.rsync-filter' .  repeated: --filter='- .rsync-filter'
-     --exclude=PATTERN       exclude files matching PATTERN
-     --exclude-from=FILE     read exclude patterns from FILE
-     --include=PATTERN       don't exclude files matching PATTERN
-     --include-from=FILE     read include patterns from FILE
-     --files-from=FILE       read list of source-file names from FILE
- -0, --from0                 all *-from/filter files are delimited by 0s
- -s, --protect-args          no space-splitting; only wildcard special-chars
-     --address=ADDRESS       bind address for outgoing socket to daemon
-     --port=PORT             specify double-colon alternate port number
-     --sockopts=OPTIONS      specify custom TCP options
-     --blocking-io           use blocking I/O for the remote shell
-     --stats                 give some file-transfer stats
- -8, --8-bit-output          leave high-bit chars unescaped in output
- -h, --human-readable        output numbers in a human-readable format
- -i, --itemize-changes       output a change-summary for all updates
-     --out-format=FORMAT     output updates using the specified FORMAT
-     --log-file=FILE         log what we're doing to the specified FILE
-     --log-file-format=FMT   log updates using the specified FMT
-     --password-file=FILE    read daemon-access password from FILE
-     --list-only             list the files instead of copying them
-     --bwlimit=KBPS          limit I/O bandwidth; KBytes per second
-     --write-batch=FILE      write a batched update to FILE
-     --only-write-batch=FILE like --write-batch but w/o updating destination
-     --read-batch=FILE       read a batched update from FILE
-     --protocol=NUM          force an older protocol version to be used
- -4, --ipv4                  prefer IPv4
- -6, --ipv6                  prefer IPv6
-     --version               print version number

File win32gui_menu.py

-# Demonstrates some advanced menu concepts using win32gui.
-# This creates a taskbar icon which has some fancy menus (but note that
-# selecting the menu items does nothing useful - see win32gui_taskbar.py
-# for examples of this.
-
-# NOTE: This is a work in progress.  Todo:
-# * The "Checked" menu items don't work correctly - I'm not sure why.
-# * No support for GetMenuItemInfo.
-
-# Based on Andy McKay's demo code.
-from win32api import *
-# Try and use XP features, so we get alpha-blending etc.
-try:
-    from winxpgui import *
-except ImportError:
-    from win32gui import *
-from win32gui_struct import *
-import win32con
-import sys, os
-import wx
-app=wx.App(0)
-this_dir = os.path.split(sys.argv[0])[0]
-
-class MainWindow:
-    def __init__(self):
-        message_map = {
-                win32con.WM_DESTROY: self.OnDestroy,
-                win32con.WM_COMMAND: self.OnCommand,
-                win32con.WM_USER+20 : self.OnTaskbarNotify,
-        }
-        # Register the Window class.
-        wc = WNDCLASS()
-        hinst = wc.hInstance = GetModuleHandle(None)
-        wc.lpszClassName = "my rsync"
-        wc.lpfnWndProc = message_map # could also specify a wndproc.
-        classAtom = RegisterClass(wc)
-        # Create the Window.
-        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
-        self.hwnd = CreateWindow( classAtom, "", style, \
-                0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, \
-                0, 0, hinst, None)
-        UpdateWindow(self.hwnd)
-        iconPathName = os.path.abspath(os.path.join( sys.prefix, "pyc.ico" ))
-        # py2.5 includes the .ico files in the DLLs dir for some reason.
-        if not os.path.isfile(iconPathName):
-            iconPathName = os.path.abspath(os.path.join( os.path.split(sys.executable)[0], "DLLs", "pyc.ico" ))
-        if not os.path.isfile(iconPathName):
-            # Look in the source tree.
-            iconPathName = os.path.abspath(os.path.join( os.path.split(sys.executable)[0], "..\\PC\\pyc.ico" ))
-        if os.path.isfile(iconPathName):
-            icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
-            hicon = LoadImage(hinst, iconPathName, win32con.IMAGE_ICON, 0, 0, icon_flags)
-        else:
-            iconPathName = None
-            print "Can't find a Python icon file - using default"
-            hicon = LoadIcon(0, win32con.IDI_APPLICATION)
-        self.iconPathName = iconPathName
-
-        # Load up some information about menus needed by our owner-draw code.
-        # The font to use on the menu.
-        ncm = SystemParametersInfo(win32con.SPI_GETNONCLIENTMETRICS)
-        self.font_menu = CreateFontIndirect(ncm['lfMenuFont'])
-        # spacing for our ownerdraw menus - not sure exactly what constants
-        # should be used (and if you owner-draw all items on the menu, it
-        # doesn't matter!)
-        self.menu_icon_height = GetSystemMetrics(win32con.SM_CYMENU) - 4
-        self.menu_icon_width = self.menu_icon_height
-        self.icon_x_pad = 8 # space from end of icon to start of text.
-        # A map we use to stash away data we need for ownerdraw.  Keyed
-        # by integer ID - that ID will be set in dwTypeData of the menu item.
-        self.menu_item_map = {}
-        
-        # Finally, create the menu
-        self.createMenu()
-
-        flags = NIF_ICON | NIF_MESSAGE | NIF_TIP
-        nid = (self.hwnd, 0, flags, win32con.WM_USER+20, hicon, "my rsync")
-        Shell_NotifyIcon(NIM_ADD, nid)
-
-    def createMenu(self):
-        self.hmenu = menu = CreatePopupMenu()
-        item, extras = PackMENUITEMINFO(text = "Exit",
-                                        hbmpItem=win32con.HBMMENU_MBAR_CLOSE,
-                                        wID=1000)
-        InsertMenuItem(menu, 0, 1, item)
-        item, extras = PackMENUITEMINFO(text = "Open BC rsync",
-                                        wID=1001)
-        InsertMenuItem(menu, 0, 1, item)
-
-        SetMenuDefaultItem(menu, 1001, 0)
-
-
-    def OnDestroy(self, hwnd, msg, wparam, lparam):
-        nid = (self.hwnd, 0)
-        Shell_NotifyIcon(NIM_DELETE, nid)
-        PostQuitMessage(0) # Terminate the app.
-
-    def OnTaskbarNotify(self, hwnd, msg, wparam, lparam):
-        if lparam==win32con.WM_RBUTTONUP:
-            pos = GetCursorPos()
-            SetForegroundWindow(self.hwnd)
-            TrackPopupMenu(self.hmenu, win32con.TPM_LEFTALIGN, pos[0], pos[1], 0, self.hwnd, None)
-            PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
-        elif lparam==win32con.WM_LBUTTONDBLCLK:
-            cmd = GetMenuDefaultItem(self.hmenu, False, 0)
-            if cmd == -1:
-                print "Can't find a default!"
-            self.OnCommand(hwnd, win32con.WM_COMMAND, cmd, 0)
-        return 1
-
-    def OnCommand(self, hwnd, msg, wparam, lparam):
-        id = LOWORD(wparam)
-        if id == 1000:
-            DestroyWindow(self.hwnd)
-        elif id == 1001:
-            import wx
-            wx.MessageBox('asfsa','asdfdsaf')
-        else:
-            raise Exception("OnCommand for ID %d" % id)
-
-def main():
-    w=MainWindow()
-    PumpMessages()
-
-if __name__=='__main__':
-    main()