1. TortoiseHg
  2. TortoiseHg
  3. thg

Source

thg / tortoise / contextmenu.py

  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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# Published under the GNU GPL, v2 or later.
# Copyright (C) 2007 Jelmer Vernooij <jelmer@samba.org>
# Copyright (C) 2007 Henry Ludemann <misc@hl.id.au>
# Copyright (C) 2007 TK Soh <teekaysoh@gmail.com>

import os
import tempfile
import pythoncom
from win32com.shell import shell, shellcon
import win32con
import win32process
import win32event
import win32ui
import win32gui
import win32gui_struct
import win32api
import _winreg
from mercurial import hg, ui, repo
from thgutil import *

S_OK = 0
S_FALSE = 1

class TortoiseMenu(object):
    def __init__(self, menutext, helptext, handler, icon=None, state=True):
        self.menutext = menutext
        self.helptext = helptext
        self.handler = handler
        self.state = state
        self.icon = icon

class TortoiseSubmenu(object):
    def __init__(self, menutext, menus=[], icon=None):
        self.menutext = menutext
        self.menus = menus[:]
        self.icon = icon
        
    def add_menu(self, menutext, helptext, handler, icon=None, state=True):
        self.menus.append(TortoiseMenu(menutext, helptext, handler, icon, state))
        
    def get_menus(self):
        return self.menus
        
class TortoiseMenuSep(object):
    def __init__(self):
        pass
    
def open_repo(path):
    root = find_root(path)
    if root:
        try:
            repo = hg.repository(ui.ui(), path=root)
            return repo
        except repo.RepoError:
            pass

    return None

def open_dialog(cmd, cmdopts='', cwd=None, root=None, filelist=[], title=None, notify=False):
    app_path = find_path("hgproc", get_prog_root(), '.EXE;.BAT')
    print "proc app = ", app_path

    if filelist:
        fd, tmpfile = tempfile.mkstemp(prefix="tortoisehg_filelist_")
        os.write(fd, "\n".join(filelist))
        os.close(fd)

    # start gpopen
    gpopts = "--command %s" % cmd
    if root:
        gpopts += " --root %s" % shellquote(root)
    if filelist:
        gpopts += " --listfile %s --deletelistfile" % (shellquote(tmpfile))
    if notify:
        gpopts += " --notify"
    if title:
        gpopts += " --title %s" % shellquote(title)
    if cwd:
        gpopts += " --cwd %s" % shellquote(cwd)

    cmdline = '%s %s -- %s' % (shellquote(app_path), gpopts, cmdopts)

    try:
        run_program(cmdline)
    except win32api.error, details:
        win32ui.MessageBox("Error executing command - %s" % (details), "gpopen")
    print "open_dialog: done"

def get_clone_repo_name(dir, repo_name):
    dest_clone = os.path.join(dir, repo_name)
    if os.path.exists(dest_clone):
        dest_clone = os.path.join(dir, "Clone of " + repo_name)

    i = 2
    while os.path.exists(dest_clone):
        dest_clone = os.path.join(dir, "Clone of (%s) %s" % (i, repo_name))
        i += 1
    return dest_clone

def run_program(cmdline):
    print "run_program: %s" % (cmdline)

    import subprocess
    pop = subprocess.Popen(cmdline, 
                           shell=False,
                           creationflags=win32con.CREATE_NO_WINDOW,
                           stderr=subprocess.STDOUT,
                           stdout=subprocess.PIPE,
                           stdin=subprocess.PIPE)
    print "run_program: done"
    
"""Windows shell extension that adds context menu items to Mercurial repository"""
class ContextMenuExtension:
    _reg_progid_ = "Mercurial.ShellExtension.ContextMenu"
    _reg_desc_ = "Mercurial Shell Extension"
    _reg_clsid_ = "{EEE9936B-73ED-4D45-80C9-AF918354F885}"
    _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
    _public_methods_ = [
        "Initialize", # From IShellExtInit
        "QueryContextMenu", "InvokeCommand", "GetCommandString" # IContextMenu
        ]

    registry_keys = [
        (_winreg.HKEY_CLASSES_ROOT, r"*\shellex\ContextMenuHandlers\TortoiseHg"),
        (_winreg.HKEY_CLASSES_ROOT, r"Directory\Background\shellex\ContextMenuHandlers\TortoiseHg"),
        (_winreg.HKEY_CLASSES_ROOT, r"Directory\shellex\ContextMenuHandlers\TortoiseHg"),
        (_winreg.HKEY_CLASSES_ROOT, r"Folder\shellex\ContextMenuHandlers\TortoiseHg"),
        (_winreg.HKEY_CLASSES_ROOT, r"Directory\shellex\DragDropHandlers\TortoiseHg"),
        (_winreg.HKEY_CLASSES_ROOT, r"Folder\shellex\DragDropHandlers\TortoiseHg"),
        ]

    def __init__(self):
        print "ContextMenuExtension: __init__ called"
        self._folder = None
        self._filenames = []
        self._handlers = {}

    def Initialize(self, folder, dataobj, hkey):
        print "Initialize: cwd = ", os.getcwd()
        if folder:
            self._folder = shell.SHGetPathFromIDList(folder)
            print "folder = ", self._folder

        if dataobj:
            format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
            sm = dataobj.GetData(format_etc)
            num_files = shell.DragQueryFile(sm.data_handle, -1)
            for i in range(num_files):
                self._filenames.append(shell.DragQueryFile(sm.data_handle, i))

    def _create_menu(self, parent, menus, pos, idCmd, idCmdFirst):
        for menu_info in menus:
            if type(menu_info) == TortoiseMenuSep:
                win32gui.InsertMenu(parent, pos, 
                        win32con.MF_BYPOSITION|win32con.MF_SEPARATOR, 
                        idCmdFirst + idCmd, None)
            elif type(menu_info) == TortoiseSubmenu:
                submenu = win32gui.CreatePopupMenu()
                idCmd = self._create_menu(submenu, menu_info.get_menus(), 0,
                        idCmd, idCmdFirst)
                opt = {
                    'text' : menu_info.menutext,
                    'wID' : idCmdFirst + idCmd,
                    'hSubMenu' : submenu, 
                }

                if menu_info.icon:
                    icon_path = get_icon_path("tortoise", menu_info.icon)
                    opt['hbmpChecked'] = opt['hbmpUnchecked'] = \
                            icon_to_bitmap(icon_path, type="MENUCHECK")
                
                item, _ = win32gui_struct.PackMENUITEMINFO(**opt)
                win32gui.InsertMenuItem(parent, pos, True, item)
                self._handlers[idCmd] = ("", lambda x,y: 0)
            elif type(menu_info) == TortoiseMenu:
                fstate = win32con.MF_BYCOMMAND
                if menu_info.state is False:
                    fstate |= win32con.MF_GRAYED
                
                opt = {
                    'text' : menu_info.menutext,
                    'fState' : fstate,
                    'wID' : idCmdFirst + idCmd,
                }

                if menu_info.icon:
                    icon_path = get_icon_path("tortoise", menu_info.icon)
                    opt['hbmpChecked'] = opt['hbmpUnchecked'] = \
                            icon_to_bitmap(icon_path, type="MENUCHECK")
                
                item, _ = win32gui_struct.PackMENUITEMINFO(**opt)
                win32gui.InsertMenuItem(parent, pos, True, item)
                self._handlers[idCmd] = (menu_info.helptext, menu_info.handler)
            idCmd += 1
            pos += 1
        return idCmd

    def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
        if uFlags & shellcon.CMF_DEFAULTONLY:
            return 0

        # only support Overlays In Explorer
        print "QueryContextMenu: checking if in explorer"
        modname = win32api.GetModuleFileName(win32api.GetModuleHandle(None))
        print "modname = %s" % modname
        if not modname.lower().endswith("\\explorer.exe"):
            print "QueryContextMenu: not in explorer"
            return 0 

        thgmenu = []    # hg menus

        # a brutal hack to detect if we are the first menu to go on to the 
        # context menu. If we are not the first, then add a menu separator
        # The number '30000' is just a guess based on my observation
        print "idCmdFirst = ", idCmdFirst
        if idCmdFirst >= 30000:
            thgmenu.append(TortoiseMenuSep())
            
        # As we are a context menu handler, we can ignore verbs.
        self._handlers = {}
        if self._folder and self._filenames:
            # get menus with drag-n-drop support
            commands = self._get_commands_dragdrop()
        else:
            # add regularly used commit menu to main context menu
            rpath = self._folder or self._filenames[0]
            if open_repo(rpath):
                thgmenu.append(TortoiseMenu(_("HG Commit..."), 
                               _("Commit changes in repository"),
                               self._commit))
                               
            # get other menus for hg submenu
            commands = self._get_commands()

        # create submenus with Hg commands
        thgmenu.append(TortoiseSubmenu("TortoiseHG", commands, icon="hg.ico"))
        thgmenu.append(TortoiseMenuSep())
        
        idCmd = self._create_menu(hMenu, thgmenu, indexMenu, 0, idCmdFirst)

        # Return total number of menus & submenus we've added
        return idCmd

    def _get_commands_dragdrop(self):
        """
        Get a list of commands valid for the current selection.

        Each command is a tuple containing (display text, handler).
        """
        
        print "_get_commands_dragdrop() on %s" % ", ".join(self._filenames)        

        # we can only accept dropping one item
        if len(self._filenames) > 1:
            return []

        # open repo
        drag_repo = None
        drop_repo = None
        
        print "drag = %s" % self._filenames[0]
        print "drop = %s" % self._folder
        
        drag_path = self._filenames[0]
        drag_repo = open_repo(drag_path)
        if not drag_repo:
            return []
        if drag_repo and drag_repo.root != drag_path:
            return []   # dragged item must be a hg repo root directory
        print "drag root = %s" % drag_repo.root

        drop_repo = open_repo(self._folder)

        print "_get_commands_dragdrop(): adding hg commands"
        
        result = []
        result.append(TortoiseMenu(_("Create Clone"), 
                       _("Create clone here from source"),
                       self._clone_here))

        if drop_repo:
            print "_get_commands_dragdrop(): drop zone is a hg repo too"
            print "drop root = %s" % drag_repo.root
            result.append(TortoiseMenu(_("Synchronize"),
                           _("Synchronize with dragged repository"),
                           self._synch_here))
        return result
        
    def _get_commands(self):
        """
        Get a list of commands valid for the current selection.

        Each command is a tuple containing (display text, handler).
        """
        
        print "_get_commands() on %s" % ", ".join(self._filenames)        

        # open repo
        result = []
        rpath = self._folder or self._filenames[0]
        repo = open_repo(rpath)
        if repo is None:
            print "%s: not in repo" % rpath
            
            result.append(TortoiseMenu(_("Create Repository Here"),
                           _("create a new repository in this directory"),
                           self._init))
            result.append(TortoiseMenu(_("Clone a Repository"),
                           _("clone a repository"),
                           self._clone))
        else:
            print "_get_commands(): adding hg commands"
            
            # Working directory status (gstatus, internal)
            result.append(TortoiseMenu(_("View File Status"),
                           _("Repository status"),
                           self._status))

            # Mercurial standard commands
            result.append(TortoiseMenu(_("Show Diff"),
                           _("View changes"),
                           self._diff))

            # Visual Diff (any extdiff command)
            result.append(TortoiseMenu(_("Visual Diff"),
                           _("View changes using GUI diff tool"),
                           self._vdiff))
                           
            result.append(TortoiseMenu(_("Add Files"),
                           _("Add files to Hg repository"),
                           self._add))
            result.append(TortoiseMenu(_("Remove Files"),
                           _("Remove selected files on the next commit"),
                           self._remove))
            result.append(TortoiseMenu(_("Undo Changes"),
                           _("Revert selected files"),
                           self._revert))

            result.append(TortoiseMenuSep())
            result.append(TortoiseMenu(_("Checkout Revision"),
                           _("update working directory"),
                           self._update))
            result.append(TortoiseMenu(_("Merge Revisions"),
                           _("merge working directory with another revision"),
                           self._merge))

            # if repo is in merging state, add menu to signal that
            if len(repo.workingctx().parents()) > 1:
                result.append(TortoiseMenu(_("Undo Merge"),
                               _("Undo merge by updating to revision"),
                               self._update))
                
            result.append(TortoiseMenuSep())

            # Visual history (hgk, hgview, glog, or internal)
            result.append(TortoiseMenu(_("View Changelog"),
                           _("View revision history"),
                           self._history))
            result.append(TortoiseMenu(_("Revision Graph"),
                           _("View history with DAG graph"),
                           self._view))
            result.append(TortoiseMenu(_("Current Revision Status..."),
                           _("Show various revision info"),
                           self._tip))

            result.append(TortoiseMenuSep())

            result.append(TortoiseMenu(_("View Tags"),
                           _("list repository tags"),
                           self._show_tags))
            result.append(TortoiseMenu(_("Add Tag"),
                           _("add a tag for the current or given revision"),
                           self._add_tag))

            result.append(TortoiseMenuSep())

            result.append(TortoiseMenu(_("Create Clone"),
                           _("Clone a repository here"),
                           self._clone))
            result.append(TortoiseMenu(_("Synchronize..."),
                           _("Synchronize with remote repository"),
                           self._synch))
            result.append(TortoiseMenu(_("Web Server"),
                           _("start web server for this repository"),
                           self._serve))

            # repo recovery functions
            rcmenu = TortoiseSubmenu(_("Repo Recovery"))
            result.append(rcmenu)
            
            rcmenu.add_menu(_("Rollback"),
                            _("Rollback the last transaction"),
                            self._rollback)
            rcmenu.add_menu(_("Recover"),
                            _("Recover from an interrupted commit or pull"),
                            self._recover)
            rcmenu.add_menu(_("Verify"),
                            _("Verify repository consistency"),
                            self._verify)

            # Optionally add an Options submenu
            c = ui.ui().config('tortoisehg', 'hgconfig', None)
            if c in ['1', 'yes', 'True']:
                result.append(TortoiseMenuSep())
                optmenu = TortoiseSubmenu(_("Options"))
                
                optmenu.add_menu(_("Username"),
                                 _("Configure username"),
                                 self._uname)
                optmenu.add_menu(_("Paths"),
                                 _("Configure remote paths"),
                                 self._paths)
                optmenu.add_menu(_("Web"),
                                 _("Configure repository web data"),
                                 self._web)
                        
                result.append(optmenu)

            result.append(TortoiseMenuSep())
            result.append(TortoiseMenu(_("Help"),
                           _("Basic Mercurial help text"),
                           self._help))

        return result

    def InvokeCommand(self, ci):
        mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
        if verb >> 16:
            # This is a textual verb invocation... not supported.
            return S_FALSE
        if verb not in self._handlers:
            raise Exception("Unsupported command id %i!" % verb)
        self._handlers[verb][1](hwnd)

    def GetCommandString(self, cmd, uFlags):
        if uFlags & shellcon.GCS_VALIDATEA or uFlags & shellcon.GCS_VALIDATEW:
            if cmd in self._handlers:
                return S_OK
            return S_FALSE
        if uFlags & shellcon.GCS_VERBA or uFlags & shellcon.GCS_VERBW:
            return S_FALSE
        if uFlags & shellcon.GCS_HELPTEXTA or uFlags & shellcon.GCS_HELPTEXTW:
            # The win32com.shell implementation encodes the resultant
            # string into the correct encoding depending on the flags.
            return self._handlers[cmd][0]
        return S_FALSE

    def _commit(self, parent_window):
        '''[tortoisehg] commit = [qct | gcommit | internal]'''
        ct = ui.ui().config('tortoisehg', 'commit', 'internal')
        if ct == 'internal':
            self._commit_simple(parent_window)
            return
        hgpath = find_path('hg', get_prog_root())
        if hgpath:
            targets = self._filenames or [self._folder]
            root = find_root(targets[0])
            cmd = "%s --repository %s %s" % \
                    (shellquote(hgpath), shellquote(root), ct)
            run_program(cmd)

    def _uname(self, parent_window):
        hgpath = find_path('hg', get_prog_root())
        if not hgpath: return
        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        cmd = "%s --repository %s config username" % (shellquote(hgpath), 
                shellquote(root))
        run_program(cmd)

    def _paths(self, parent_window):
        hgpath = find_path('hg', get_prog_root())
        if not hgpath: return
        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        cmd = "%s --repository %s config paths" % (shellquote(hgpath), 
                shellquote(root))
        run_program(cmd)

    def _web(self, parent_window):
        hgpath = find_path('hg', get_prog_root())
        if not hgpath: return
        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        cmd = "%s --repository %s config web" % (shellquote(hgpath), 
                shellquote(root))
        run_program(cmd)

    def _vdiff(self, parent_window):
        '''[tortoisehg] vdiff = <any extdiff command>'''
        diff = ui.ui().config('tortoisehg', 'vdiff', None)
        if not diff:
            msg = "You must configure tortoisehg.vdiff in your Mercurial.ini"
            title = "Visual Diff Not Configured"
            win32ui.MessageBox(msg, title, win32con.MB_OK|win32con.MB_ICONERROR)
            return
        hgpath = find_path('hg', get_prog_root())
        if hgpath:
            targets = self._filenames or [self._folder]
            root = find_root(targets[0])
            quoted_files = [shellquote(s) for s in targets]
            cmd = "%s --repository %s %s %s" %  \
                (shellquote(hgpath), shellquote(root),
                   diff, " ".join(quoted_files))
            run_program(cmd)

    def _view(self, parent_window):
        '''[tortoisehg] view = [hgk | hgview]'''
        view = ui.ui().config('tortoisehg', 'view', '')
        if not view:
            msg = "You must configure tortoisehg.view in your Mercurial.ini"
            title = "Revision Graph Tool Not Configured"
            win32ui.MessageBox(msg, title, win32con.MB_OK|win32con.MB_ICONERROR)
            return

        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        if view == 'hgview':
            hgviewpath = find_path('hgview')
            cmd = "%s --repository=%s" % \
                    (shellquote(hgviewpath), shellquote(root))
            if len(self._filenames) == 1:
                cmd += " --file=%s" % shellquote(self._filenames[0])
            run_program(cmd)
        else:
            hgpath = find_path('hg', get_prog_root())
            if not hgpath: return
            if view == 'hgk':
                cmd = "%s --repository %s view" % \
                        (shellquote(hgpath), shellquote(root))
                run_program(cmd)
            else:
                msg = "Revision graph viewer %s not recognized" % view
                title = "Unknown history tool"
                win32ui.MessageBox(msg, title, win32con.MB_OK|win32con.MB_ICONERROR)

    def _history(self, parent_window):
        '''[tortoisehg] log = [glog | internal]'''
        log = ui.ui().config('tortoisehg', 'log', 'internal')
        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        if log == 'internal':
            self._log(parent_window)
        else:
            hgpath = find_path('hg', get_prog_root())
            if not hgpath: return
            if log == 'glog':
                quoted_files = [shellquote(s) for s in targets]
                cmd = "%s --repository %s glog %s" % \
                        (shellquote(hgpath), shellquote(root),
                         " ".join(quoted_files))
                run_program(cmd)
            else:
                msg = "History viewer %s not recognized" % log
                title = "Unknown history tool"
                win32ui.MessageBox(msg, title, win32con.MB_OK|win32con.MB_ICONERROR)

    def _clone_here(self, parent_window):
        src = self._filenames[0]
        dest = self._folder
        repo_name = os.path.basename(src)
        dest_clone = get_clone_repo_name(dest, repo_name)
        cmdopts = "--verbose"
        repos = [src, dest_clone]
        open_dialog('clone', cmdopts, cwd=dest, filelist=repos)

    def _push_here(self, parent_window):
        src = self._filenames[0]
        dest = self._folder
        msg = "Push changes from %s into %s?" % (src, dest)
        title = "Mercurial: push"
        rv = win32ui.MessageBox(msg, title, win32con.MB_OKCANCEL)
        if rv == 2:
            return

        cmdopts = "--verbose"
        open_dialog('push', cmdopts, root=src, filelist=[dest])

    def _pull_here(self, parent_window):
        src = self._filenames[0]
        dest = self._folder
        msg = "Pull changes from %s?" % (src)
        title = "Mercurial: pull"
        rv = win32ui.MessageBox(msg, title, win32con.MB_OKCANCEL)
        if rv == 2:
            return

        cmdopts = "--verbose"
        open_dialog('pull', cmdopts, root=src, filelist=[dest])

    def _incoming_here(self, parent_window):
        src = self._filenames[0]
        dest = self._folder
        cmdopts = "--verbose"
        open_dialog('incoming', cmdopts, root=src, filelist=[dest])

    def _outgoing_here(self, parent_window):
        src = self._filenames[0]
        dest = self._folder
        cmdopts = "--verbose"
        open_dialog('outgoing', cmdopts, root=src, filelist=[dest])

    def _init(self, parent_window):
        dest = self._folder or self._filenames[0]
        msg = "Create Hg repository in %s?" % (dest)
        title = "Mercurial: init"
        rv = win32ui.MessageBox(msg, title, win32con.MB_OKCANCEL)
        if rv == 2:
            return
        try:
            hg.repository(ui.ui(), dest, create=1)
        except:
            msg = "Error creating repo"
            win32ui.MessageBox(msg, title, 
                               win32con.MB_OK|win32con.MB_ICONERROR)
            
    def _status(self, parent_window):
        '''[tortoisehg] status = [gstatus | internal]'''
        stat = ui.ui().config('tortoisehg', 'status', 'internal')
        if stat == 'internal':
            self._run_dialog('status')
        elif stat == 'gstatus':
            targets = self._filenames or [self._folder]
            root = find_root(targets[0])
            quoted_files = [shellquote(s) for s in targets]
            hgpath = find_path('hg', get_prog_root())
            cmd = "%s --repository %s gstatus %s" % \
                    (shellquote(hgpath), shellquote(root),
                     " ".join(quoted_files))
            run_program(cmd)
        else:
            msg = "Status viewer %s not recognized" % stat
            title = "Unknown status tool"
            win32ui.MessageBox(msg, title, win32con.MB_OK|win32con.MB_ICONERROR)

    def _clone(self, parent_window):
        self._run_dialog('clone', True)

    def _synch(self, parent_window):
        self._run_dialog('synch', True)

    def _synch_here(self, parent_window):
        self._run_dialog('synch', False)
        
    def _pull(self, parent_window):
        self._run_dialog('pull', True)

    def _push(self, parent_window):
        self._run_dialog('push', True)

    def _incoming(self, parent_window):
        self._run_dialog('incoming', True)

    def _outgoing(self, parent_window):
        self._run_dialog('outgoing', True)

    def _serve(self, parent_window):
        self._run_dialog('serve', noargs=True)

    def _add(self, parent_window):
        self._run_dialog('add', modal=True)

    def _remove(self, parent_window):
        self._run_dialog('remove')

    def _revert(self, parent_window):
        self._run_dialog('status')

    def _tip(self, parent_window):
        self._run_dialog('tip', True)

    def _parents(self, parent_window):
        self._run_dialog('parents', True)

    def _heads(self, parent_window):
        self._run_dialog('heads', True)

    def _log(self, parent_window):
        self._run_dialog('log', verbose=False)

    def _show_tags(self, parent_window):
        self._run_dialog('tags', True, verbose=False)

    def _add_tag(self, parent_window):
        self._run_dialog('tag', True, verbose=False)

    def _diff(self, parent_window):
        self._run_dialog('diff')

    def _merge(self, parent_window):
        self._run_dialog('merge', noargs=True)

    def _rollback(self, parent_window):
        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        msg = "Confirm rollback: %s" % root
        title = "Mercurial: rollback"
        rv = win32ui.MessageBox(msg, title, win32con.MB_OKCANCEL)
        if rv == 1:
            self._run_dialog('rollback', noargs=True)

    def _recover(self, parent_window):
        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        msg = "Confirm recovering %s?" % root
        title = "Mercurial: recover"
        rv = win32ui.MessageBox(msg, title, win32con.MB_OKCANCEL)
        if rv == 1:
            self._run_dialog('recover', noargs=True)

    def _verify(self, parent_window):
        self._run_dialog('verify', noargs=True)

    def _commit_simple(self, parent_window):
        self._run_dialog('commit')

    def _update(self, parent_window):
        self._run_dialog('update', noargs=True)

    def _run_dialog(self, hgcmd, noargs=False, verbose=True, modal=False):
        if self._folder:
            cwd = self._folder
        elif self._filenames:
            f = self._filenames[0]
            cwd = os.path.isdir(f) and f or os.path.dirname(f)
        else:
            win32ui.MessageBox("Can't get cwd!", 'Hg ERROR', 
                   win32con.MB_OK|win32con.MB_ICONERROR)
            return

        targets = self._filenames or [self._folder]
        root = find_root(targets[0])
        filelist = []
        if noargs == False:
            filelist = targets
        cmdopts = "%s" % (verbose and "--verbose" or "")
        print "_run_program_dialog: cmdopts = ", cmdopts
        title = "Hg %s" % hgcmd
        open_dialog(hgcmd, cmdopts, cwd=cwd, root=root, filelist=filelist)

    def _help(self, parent_window):
        open_dialog('help', '--verbose')