示例#1
0
 def __init__(self, title, message, parent, choices, default=None,
              esc=None, files=None):
     gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_MODAL,
             gtk.MESSAGE_QUESTION)
     self.set_title(hglib.toutf(title))
     if files:
         msg = ''
         for i, file in enumerate(files):
             msg += '   %s\n' % file
             if i == 9:
                 msg += '   ...\n'
                 break
         message += '\n\n' + msg
     self.format_secondary_markup(gtklib.markup(hglib.toutf(message),
                                  weight='bold'))
     accel_group = gtk.AccelGroup()
     self.add_accel_group(accel_group)
     for i, s in enumerate(choices):
         button = self.add_button(s.replace('&', '_'), i)
         try:
             char = s[s.index('&')+1].lower()
             button.add_accelerator('clicked', accel_group, ord(char),
                                    0, gtk.ACCEL_VISIBLE)
         except ValueError:
             pass
     if default:
         self.set_default_response(default)
     self.esc = esc
示例#2
0
 def annotate_wait(self, thread, q, tview, curdate, colormap, frame, rows):
     """
     Handle all the messages currently in the queue (if any).
     """
     model = tview.get_model()
     while q.qsize():
         line = q.get(0).rstrip('\r\n')
         try:
             (revpath, text) = line.split(':', 1)
             revid, path = revpath.lstrip().split(' ', 1)
             rowrev = long(revid)
         except ValueError:
             continue
         desc, user = self.get_rev_desc(rowrev)
         ctx = self.repo[rowrev]
         color = colormap.get_color(ctx, curdate)
         if self.tabwidth:
             text = text.expandtabs(self.tabwidth)
         model.append((revid, hglib.toutf(text[:512]), desc,
                 hglib.toutf(path.strip()), color, user, len(model)+1))
     if thread.isAlive():
         return True
     else:
         if threading.activeCount() == 1:
             self.stop_button.set_sensitive(False)
         if rows:
             tview.get_selection().select_path(rows[0])
             tview.scroll_to_cell(rows[0], use_align=True, row_align=0.5)
             tview.grab_focus()
         frame._mythread = None
         self.stbar.end()
         return False
示例#3
0
    def load_patch_details_from_file_object(self, pf, patchfile, isTemp=False):
        """ Load patch details into buffer and file list
        :param pf: open file object
        :param patchfile: path and name of patch file
        :param isTemp: if True, then pf is a temporary file 
            and patchfile does not exist
        """
        self._filelist.clear()
        self._filelist.append(('*', _('[All Files]'), ''))

        # append files & collect hunks
        self.currev = -1
        self.curphunks = {}
        self.curpatch = patchfile
        if isTemp:
            # pf is a temporary, so update panel cache while we can
            patch_ctx = csinfo.patchctx(patchfile, self.repo, patchHandle=pf)
            self.summarypanel.update(patch_ctx, self.patchstyle)
            pf.seek(0)
        def get_path(a, b):
            type = (a == '/dev/null') and 'A' or 'M'
            type = (b == '/dev/null') and 'R' or type
            rawpath = (b != '/dev/null') and b or a
            if not (rawpath.startswith('a/') or rawpath.startswith('b/')):
                return type, rawpath
            return type, rawpath.split('/', 1)[-1]
        hunks = []
        files = []
        map = {'MODIFY': 'M', 'ADD': 'A', 'DELETE': 'R',
               'RENAME': '', 'COPY': ''}
        try:
            try:
                for state, values in patch.iterhunks(self.ui, pf):
                    if state == 'git':
                        for m in values:
                            f = m.path
                            self._filelist.append((map[m.op], hglib.toutf(f), f))
                            files.append(f)
                    elif state == 'file':
                        type, path = get_path(values[0], values[1])
                        self.curphunks[path] = hunks = ['diff']
                        if path not in files:
                            self._filelist.append((type, hglib.toutf(path), path))
                            files.append(path)
                    elif state == 'hunk':
                        hunks.extend([l.rstrip('\r\n') for l in values.hunk])
                    else:
                        raise _('unknown hunk type: %s') % state
            except patch.PatchError:
                pass
        finally:
            pf.close()

        # select first file
        if len(self._filelist) > 1:
            self._filesel.select_path((1,))
        else:
            self._filesel.select_path((0,))

        self.reset_scroll_pos()
示例#4
0
 def grep_wait(self, thread, q, model, search_hbox, regexp, frame):
     """
     Handle all the messages currently in the queue (if any).
     """
     text = ''
     while q.qsize():
         data, label = q.get(0)
         data = gtklib.markup_escape_text(hglib.toutf(data))
         if label == 'grep.match':
             text += '<span foreground="red"><b>%s</b></span>' % data
         else:
             text += data
     
     for line in text.splitlines():
         try:
             (path, revid, text) = line.split(':', 2)
             desc, user = self.get_rev_desc(long(revid))
         except ValueError:
             continue
         if self.tabwidth:
             text = text.expandtabs(self.tabwidth)
         model.append((revid, text, desc, hglib.toutf(path)))
     if thread.isAlive():
         return True
     else:
         if threading.activeCount() == 1:
             self.stop_button.set_sensitive(False)
         frame._mythread = None
         search_hbox.set_sensitive(True)
         regexp.grab_focus()
         self.stbar.end()
         return False
示例#5
0
def _get_known_branch_colors(repo):
    global known_branch_colors

    repo_setting = repo.ui.config('tortoisehg', 'branchcolors')

    if known_branch_colors:
        branch_colors, setting = known_branch_colors
        if repo_setting == setting:
            return branch_colors

    branchcolors = repo_setting
    if not branchcolors:
        return {}

    branchcolors = hglib.tounicode(branchcolors)
    branchcolors = [x for x in re.split(r'(?:(?<=\\\\)|(?<!\\)) ', branchcolors) if x]
    values = {}
    for branchcolor in branchcolors:
        parts = re.split(r'(?:(?<=\\\\)|(?<!\\)):', branchcolor)
        if len(parts) != 2:
            continue # ignore badly formed entry

        # Mercurial branch names are encoded in utf-8 so we must
        # make sure to encode back to that after having unescaped
        # the string.
        branch_name = hglib.toutf(parts[0].replace('\\:', ':').replace('\\ ', ' ').decode('unicode_escape'))
        values[branch_name] = hglib.toutf(parts[1])

    known_branch_colors = values, repo_setting
    return values
示例#6
0
 def selpretty(self, selected):
     str = ''
     for h in self.header:
         if h.startswith('index '):
             str += _('this modifies a binary file (all or nothing)\n')
             break
         if self.pretty_re.match(h):
             str += hglib.toutf(h)
             if self.binary():
                 str += _('this is a binary file\n')
             break
         if h.startswith('---'):
             hunks = len(self.hunks)
             shunks, lines, slines = 0, 0, 0
             for i, h in enumerate(self.hunks):
                 lines += h.added + h.removed
                 if selected(i):
                     shunks += 1
                     slines += h.added + h.removed
             str += '<span foreground="blue">'
             str += _('total: %d hunks (%d changed lines); '
                     'selected: %d hunks (%d changed lines)') % (hunks,
                             lines, shunks, slines)
             str += '</span>'
             break
         str += hglib.toutf(h)
     return str
示例#7
0
 def _set_path(self, uri):
     if not uri.startswith('file://'):
         return
     path = urllib.unquote(uri[7:])
     if paths.find_root(path) == path:
         self.pathtext.set_text(hglib.toutf(path))
     elif not os.path.isdir(path) and path.endswith('.hg'):
         self.pathtext.set_text(hglib.toutf(path))
示例#8
0
    def process_queue(self):
        """
        Handle all the messages currently in the queue (if any).
        """
        self.hgthread.process_dialogs()
        enditer = self.textbuffer.get_end_iter()
        while self.hgthread.geterrqueue().qsize():
            try:
                tags = gtklib.gettags('ui.error')
                msg = hglib.toutf(self.hgthread.geterrqueue().get(0))
                self.textbuffer.insert_with_tags_by_name(enditer, msg, *tags)
                self.textview.scroll_to_mark(self.textbuffer.get_insert(), 0)
            except Queue.Empty:
                pass
        while self.stdoutq.qsize():
            try:
                tags = gtklib.gettags('ui.error')
                msg = hglib.toutf(self.stdoutq.get(0))
                self.textbuffer.insert_with_tags_by_name(enditer, msg, *tags)
                self.textview.scroll_to_mark(self.textbuffer.get_insert(), 0)
            except Queue.Empty:
                pass
        while self.hgthread.getqueue().qsize():
            try:
                msg, label = self.hgthread.getqueue().get(0)
                msg = hglib.toutf(msg)
                tags = gtklib.gettags(label)
                if tags:
                    self.textbuffer.insert_with_tags_by_name(enditer, msg, *tags)
                else:
                    self.textbuffer.insert(enditer, msg)
                self.textview.scroll_to_mark(self.textbuffer.get_insert(), 0)
            except Queue.Empty:
                pass

        self.update_progress()
        if not self.hgthread.isAlive():
            self.returncode = self.hgthread.return_code()
            if self.returncode is None:
                self.write(_('\n[command interrupted]'))
            elif self.returncode == 0 and self.cmdlist:
                cmdline = self.cmdlist.pop(0)
                text = '\n' + hglib.toutf(' '.join(cmdline)) + '\n'
                self.textbuffer.insert(enditer, text)
                self.textview.scroll_to_mark(self.textbuffer.get_insert(), 0)
                self.hgthread = hgthread.HgThread(cmdline[1:])
                self.hgthread.start()
                return True
            self._button_stop.set_sensitive(False)
            self._button_ok.set_sensitive(True)
            self._button_ok.grab_focus()
            if os.name == 'nt':
                os.dup2(self.oldstdout, sys.__stdout__.fileno())
                os.close(self.oldstdout)
            return False # Stop polling this function
        else:
            return True
示例#9
0
 def search_wait(self, thread, q):
     canmodel = self.cantree.get_model()
     while canmodel and q.qsize():
         source, dest, sim = q.get(0)
         canmodel.append( [source, hglib.toutf(source), dest,
                           hglib.toutf(dest), sim, True] )
     if thread.isAlive():
         return True
     else:
         self.stbar.end()
         return False
示例#10
0
 def get_rev_desc(self, rev):
     if rev in self.changedesc:
         return self.changedesc[rev]
     ctx = self.repo[rev]
     author = hglib.toutf(hglib.username(ctx.user()))
     date = hglib.toutf(hglib.displaytime(ctx.date()))
     text = hglib.tounicode(ctx.description()).replace(u'\0', '')
     lines = text.splitlines()
     summary = hglib.toutf(lines and lines[0] or '')
     desc = gtklib.markup_escape_text('%s@%s %s "%s"' % \
                                      (author, rev, date, summary))
     self.changedesc[rev] = (desc, author)
     return self.changedesc[rev]
示例#11
0
        def rundlg(q):
            from win32com.shell import shell, shellcon
            import win32gui, pywintypes

            def BrowseCallbackProc(hwnd, msg, lp, data):
                if msg == shellcon.BFFM_INITIALIZED:
                    win32gui.SendMessage(
                        hwnd, shellcon.BFFM_SETSELECTION, 1, data)
                elif msg == shellcon.BFFM_SELCHANGED:
                    # Set the status text of the
                    # For this message, 'lp' is the address of the PIDL.
                    pidl = shell.AddressAsPIDL(lp)
                    try:
                        path = shell.SHGetPathFromIDList(pidl)
                        win32gui.SendMessage(
                            hwnd, shellcon.BFFM_SETSTATUSTEXT, 0, path)
                    except shell.error:
                        # No path for this PIDL
                        pass

            fname = None
            try: 
                flags = shellcon.BIF_EDITBOX | 0x40 #shellcon.BIF_NEWDIALOGSTYLE
                pidl, _, _ = shell.SHBrowseForFolder(
                   0,
                   None,
                   hglib.fromutf(self.title),
                   flags,
                   BrowseCallbackProc, # callback function
                   self.initial)       # 'data' param for the callback
                if pidl:
                    fname = hglib.toutf(shell.SHGetPathFromIDList(pidl))
            except (pywintypes.error, pywintypes.com_error):
                pass
            q.put(fname)
示例#12
0
 def process_queue(self):
     """
     Handle all the messages currently in the queue (if any).
     """
     self.hgthread.process_dialogs()
     while self.hgthread.geterrqueue().qsize():
         try:
             msg = self.hgthread.geterrqueue().get(0)
             self.write_err(msg)
         except Queue.Empty:
             pass
     enditer = self.textbuffer.get_end_iter()
     while self.hgthread.getqueue().qsize():
         try:
             msg, label = self.hgthread.getqueue().get(0)
             msg = hglib.toutf(msg)
             tags = gtklib.gettags(label)
             if tags:
                 self.textbuffer.insert_with_tags_by_name(enditer, msg, *tags)
             else:
                 self.textbuffer.insert(enditer, msg)
             self.textview.scroll_to_mark(self.textbuffer.get_insert(), 0)
         except Queue.Empty:
             pass
     self.update_progress()
     if self._cmd_running():
         return True
     else:
         self._stop_button.set_sensitive(False)
         if self.hgthread.return_code() is None:
             self.write_err(_('[command interrupted]'))
         return False # Stop polling this function
示例#13
0
    def diff_highlight_buffer(self, difftext):
        buf = gtk.TextBuffer()
        if self.colorstyle == 'background':
            buf.create_tag('removed', paragraph_background=gtklib.PRED)
            buf.create_tag('added', paragraph_background=gtklib.PGREEN)
        elif self.colorstyle == 'none':
            buf.create_tag('removed')
            buf.create_tag('added')
        else:
            buf.create_tag('removed', foreground=gtklib.DRED)
            buf.create_tag('added', foreground=gtklib.DGREEN)
        buf.create_tag('position', foreground=gtklib.DORANGE)
        buf.create_tag('header', foreground=gtklib.DBLUE)

        bufiter = buf.get_start_iter()
        for line in difftext:
            line = hglib.toutf(line)
            if line.startswith('---') or line.startswith('+++'):
                buf.insert_with_tags_by_name(bufiter, line, 'header')
            elif line.startswith('-'):
                line = hglib.diffexpand(line)
                buf.insert_with_tags_by_name(bufiter, line, 'removed')
            elif line.startswith('+'):
                line = hglib.diffexpand(line)
                buf.insert_with_tags_by_name(bufiter, line, 'added')
            elif line.startswith('@@'):
                buf.insert_with_tags_by_name(bufiter, line, 'position')
            else:
                line = hglib.diffexpand(line)
                buf.insert(bufiter, line)
        return buf
示例#14
0
 def unknown_wait(self, thread, q):
     unkmodel = self.unktree.get_model()
     while q.qsize():
         wfile = q.get(0)
         if unkmodel is not None:
             unkmodel.append( [wfile, hglib.toutf(wfile)] )
     return thread.isAlive()
示例#15
0
    def get_body(self, vbox):
        self.prevtarget = None

        # layout table
        self.table = table = gtklib.LayoutTable()
        vbox.pack_start(table, True, True, 2)

        ## revision combo
        self.combo = gtk.combo_box_entry_new_text()
        self.combo.child.set_width_chars(28)
        self.combo.child.connect('activate',
                                 lambda b: self.response(gtk.RESPONSE_OK))
        if self.initrev == '':
            self.combo.append_text(WD_PARENT)
        else:
            self.combo.append_text(str(self.initrev))
        self.combo.set_active(0)
        for b in self.repo.branchtags():
            self.combo.append_text(b)
        tags = list(self.repo.tags())
        tags.sort()
        tags.reverse()
        for t in tags:
            self.combo.append_text(t)

        table.add_row(_('Archive revision:'), self.combo)

        self.opt_files_in_rev = gtk.CheckButton(
                    _('Only files modified/created in this revision'))
        table.add_row('', self.opt_files_in_rev, ypad=0)

        ## dest combo & browse button
        self.destentry = gtk.Entry()
        self.destentry.set_width_chars(46)

        destbrowse = gtk.Button(_('Browse...'))
        destbrowse.connect('clicked', self.browse_clicked)

        table.add_row(_('Destination path:'), self.destentry, 0, destbrowse)

        ## archive types
        self.filesradio = gtk.RadioButton(None, _('Directory of files'))
        self.filesradio.connect('toggled', self.type_changed)
        table.add_row(_('Archive types:'), self.filesradio, ypad=0)
        def add_type(label):
            radio = gtk.RadioButton(self.filesradio, label)
            radio.connect('toggled', self.type_changed)
            table.add_row(None, radio, ypad=0)
            return radio
        self.tarradio = add_type(_('Uncompressed tar archive'))
        self.tbz2radio = add_type(_('Tar archive compressed using bzip2'))
        self.tgzradio = add_type(_('Tar archive compressed using gzip'))
        self.uzipradio = add_type(_('Uncompressed zip archive'))
        self.zipradio = add_type(_('Zip archive compressed using deflate'))

        # signal handler
        self.combo.connect('changed', lambda c: self.update_path())

        # prepare to show
        self.update_path(hglib.toutf(self.repo.root))
示例#16
0
    def __init__(self, command, pats):
        gtk.Dialog.__init__(self)
        gtklib.set_tortoise_icon(self, "hg.ico")
        gtklib.set_tortoise_keys(self)
        self.set_has_separator(False)
        self.set_default_size(400, 500)
        self.connect("response", self.dialog_response)

        entry = gtk.Entry()
        self.vbox.pack_start(entry, False, True)

        def newfolder_notify(newfolder):
            curpath = entry.get_text()
            newpath = os.path.join(curpath, newfolder)
            newpath = hglib.toutf(os.path.abspath(newpath))
            root = paths.find_root(newpath)
            if root:
                self.set_title(root + " - " + _("browser"))
            else:
                self.set_title(_("browser"))
            entry.set_text(newpath)
            browse.chdir(newpath)

        browse = BrowsePane(newfolder_notify)
        scroller = gtk.ScrolledWindow()
        scroller.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroller.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        scroller.add(browse)
        self.vbox.pack_start(scroller, True, True)
        self.show_all()

        cwd = hglib.toutf(os.getcwd())
        entry.connect("activate", self.entry_activated, browse)
        entry.set_text(cwd)
        browse.chdir(cwd)
示例#17
0
 def __init__(self, title, message, parent, type=gtk.MESSAGE_INFO):
     SimpleMessage.__init__(self, parent, gtk.DIALOG_MODAL,
             type, gtk.BUTTONS_CLOSE)
     self.set_title('TortoiseHg')
     self.set_markup(gtklib.markup(hglib.toutf(title), weight='bold'))
     self.format_secondary_text(hglib.toutf(message))
     mod = gtklib.get_thg_modifier()
     key, modifier = gtk.accelerator_parse(mod+'Return')
     accel_group = gtk.AccelGroup()
     self.add_accel_group(accel_group)
     try:
         buttons = self.get_children()[0].get_children()[1].get_children()
         buttons[0].add_accelerator('clicked', accel_group, key,
                                    modifier, gtk.ACCEL_VISIBLE)
     except IndexError:
         pass
示例#18
0
 def _write(self, msg, append=True):
     msg = hglib.toutf(msg)
     if append:
         enditer = self.textbuffer.get_end_iter()
         self.textbuffer.insert(enditer, msg)
     else:
         self.textbuffer.set_text(msg)
示例#19
0
 def write(self, msg, append=True):
     msg = hglib.toutf(msg)
     if append:
         enditer = self.textbuffer.get_end_iter()
         self.textbuffer.insert(enditer, msg)
         self.textview.scroll_to_mark(self.textbuffer.get_insert(), 0)
     else:
         self.textbuffer.set_text(msg)
示例#20
0
def hunk_unmarkup(text):
    'Format a diff hunk for display in a TreeView row without markup'
    hunk = ''
    # don't use splitlines, should split with only LF for the patch
    lines = hglib.tounicode(text).split(u'\n')
    for line in lines:
        hunk += gtklib.markup(hglib.toutf(line[:512])) + '\n'
    return hunk
示例#21
0
 def rename_file(self, wfile):
     fdir, fname = os.path.split(wfile)
     utf_fname = hglib.toutf(fname)
     newfile = dialog.entry_dialog(self.stat, _('Rename file to:'),
                      True, utf_fname)
     if newfile and newfile != utf_fname:
         self.hg_move([wfile, os.path.join(fdir, hglib.fromutf(newfile))])
     return True
示例#22
0
    def __init__(self, patchpath, repo, patchHandle=None):
        """ Read patch context from file
        :param patchHandle: If set, then the patch is a temporary.
            The provided handle is used to read the patch and
            the patchpath contains the name of the patch. 
            The handle is NOT closed.
        """
        self._path = patchpath
        self._patchname = os.path.basename(patchpath)
        self._repo = repo
        if patchHandle:
            pf = patchHandle
            pf_start_pos = pf.tell()
        else:
            pf = open(patchpath)
        try:
            data = patch.extract(self._repo.ui, pf)
            tmpfile, msg, user, date, branch, node, p1, p2 = data
            if tmpfile:
                os.unlink(tmpfile)
        finally:
            if patchHandle:
                pf.seek(pf_start_pos)
            else:
                pf.close()
        if not msg and hasattr(repo, "mq"):
            # attempt to get commit message
            from hgext import mq

            msg = mq.patchheader(repo.mq.join(self._patchname)).message
            if msg:
                msg = "\n".join(msg)
        self._node = node
        self._user = user and hglib.toutf(user) or ""
        self._date = date and util.parsedate(date) or None
        self._desc = msg and msg or ""
        self._branch = branch and hglib.toutf(branch) or ""
        self._parents = []
        for p in (p1, p2):
            if not p:
                continue
            try:
                self._parents.append(repo[p])
            except (error.LookupError, error.RepoLookupError, error.RepoError):
                self._parents.append(p)
示例#23
0
 def refresh(self):
     hglib.invalidaterepo(self.repo)
     matcher = match.always(self.repo.root, self.repo.root)
     try:
         unknown = self.repo.status(match=matcher, unknown=True)[4]
     except (EnvironmentError, util.Abort), inst:
         gdialog.Prompt(_('Error while reading status'),
                        hglib.toutf(str(inst)), self).run()
         return
示例#24
0
    def get_body(self, vbox):
        # layout table
        self.table = table = gtklib.LayoutTable()
        vbox.pack_start(table, True, True, 2)

        ## target revision combo
        self.revcombo = gtk.combo_box_entry_new_text()
        table.add_row(_('Strip:'), self.revcombo)
        reventry = self.revcombo.child
        reventry.set_width_chars(32)

        ### fill combo list
        self.revcombo.append_text(self.initrev)
        self.revcombo.set_active(0)
        for name in hglib.getlivebranch(self.repo):
            self.revcombo.append_text(name)

        tags = list(self.repo.tags())
        tags.sort()
        tags.reverse()
        for tag in tags:
            self.revcombo.append_text(hglib.toutf(tag))

        def createlabel():
            label = gtk.Label()
            label.set_alignment(0, 0.5)
            label.set_size_request(-1, 24)
            label.size_request()
            return label

        ## result label
        self.resultlbl = createlabel()
        table.add_row(_('Preview:'), self.resultlbl, padding=False)

        ## changeset list
        self.cslist = cslist.ChangesetList()
        self.cslist.set_activatable_enable(True)
        table.add_row(None, self.cslist, padding=False,
                      yopt=gtk.FILL|gtk.EXPAND)

        ## options
        self.expander = gtk.Expander(_('Options:'))
        self.expander.connect('notify::expanded', self.options_expanded)

        ### force option (fixed)
        self.forceopt = gtk.CheckButton(_('Discard local changes, no backup '
                                          '(-f/--force)'))
        table.add_row(self.expander, self.forceopt)

        # signal handlers
        reventry.connect('activate', lambda b: self.response(gtk.RESPONSE_OK))
        self.revcombo.connect('changed', lambda c: self.preview(queue=True))
        self.cslist.connect('list-updated', self.preview_updated)
        self.cslist.connect('item-activated', self.item_activated)

        # prepare to show
        self.preview()
示例#25
0
    def prepare_diff(self, difflines, offset, fname):
        'Borrowed from hgview; parses changeset diffs'
        def addtag( name, offset, length ):
            if tags and tags[-1][0] == name and tags[-1][2]==offset:
                tags[-1][2] += length
            else:
                tags.append( [name, offset, offset+length] )

        add, rem = 0, 0
        for l in difflines[1:]:
            if l.startswith('+'):
                add += 1
            elif l.startswith('-'):
                rem += 1
        outlines = []
        tags = []
        txt = hglib.toutf('=== (+%d,-%d) %s ===\n' % (add, rem, fname))
        addtag( 'greybg', offset, len(txt) )
        outlines.append(txt)
        offset += len(txt.decode('utf-8'))
        for l1 in difflines[1:]:
            l = hglib.toutf(l1)
            if l.startswith('--- '):
                continue
            if l.startswith('+++ '):
                continue
            if l.startswith('@@'):
                tag = 'blue'
            elif l.startswith('+'):
                tag = 'green'
                l = hglib.diffexpand(l)
            elif l.startswith('-'):
                tag = 'red'
                l = hglib.diffexpand(l)
            else:
                tag = 'normal'
                l = hglib.diffexpand(l)
            l = l+"\n"
            length = len(l.decode('utf-8'))
            addtag( tag, offset, length )
            outlines.append( l )
            offset += length
        return tags, outlines
示例#26
0
 def _get_config(self):
     if self._root:
         try:
             repo = hg.repository(ui.ui(), path=self._root)
         except error.RepoError:
             self.destroy()
         self.defport = repo.ui.config('web', 'port') or '8000'
         self.webname = repo.ui.config('web', 'name') or \
                 os.path.basename(self._root)
     elif self._webdirconf:
         self.defport = '8000'
         self.webname = _('unknown')
         self.set_title(_('%s - serve') % (hglib.toutf(self._webdirconf)))
         return
     if self._webdirconf:
         self.set_title(_('%s serve - %s') %
                 (hglib.toutf(self._webdirconf), hglib.toutf(self.webname)))
     else:
         self.set_title(hglib.toutf(self.webname) + _(' - serve'))
示例#27
0
 def __init__(self, title, files, parent, primary):
     SimpleMessage.__init__(self, parent, gtk.DIALOG_MODAL,
             gtk.MESSAGE_QUESTION, gtk.BUTTONS_YES_NO)
     self.set_title(hglib.toutf(title))
     self.set_markup(gtklib.markup(hglib.toutf(primary), weight='bold'))
     message = ''
     for i, f in enumerate(files):
         message += '   ' + f + '\n'
         if i == 9:
             message += '   ...\n'
             break
     self.format_secondary_text(hglib.toutf(message))
     accel_group = gtk.AccelGroup()
     self.add_accel_group(accel_group)
     buttons = self.get_children()[0].get_children()[1].get_children()
     buttons[1].add_accelerator('clicked', accel_group, ord('y'),
                           0, gtk.ACCEL_VISIBLE)
     buttons[0].add_accelerator('clicked', accel_group, ord('n'),
                           0, gtk.ACCEL_VISIBLE)
示例#28
0
    def process_queue(self, callback, args, kargs):
        # process queue
        self.hgthread.process_dialogs()

        # output to buffer
        while self.hgthread.geterrqueue().qsize():
            try:
                msg = self.hgthread.geterrqueue().get(0)
                self.log.append(hglib.toutf(msg), error=True)
            except Queue.Empty:
                pass
        while self.hgthread.getqueue().qsize():
            try:
                msg, label = self.hgthread.getqueue().get(0)
                self.log.append(hglib.toutf(msg))
            except Queue.Empty:
                pass

        # update progress bar
        self.update_progress()

        # check thread
        if not self.hgthread.isAlive():
            returncode = self.hgthread.return_code()
            if returncode == 0 and not self.already_opened:
                self.set_pbar(False)
            else:
                self.set_pbar(True)
                self.switch_to(ready=True)
                self.set_buttons(stop=False, close=True)
            if returncode is None:
                self.log.append(_('\n[command interrupted]'))
            if not returncode == 0:
                self.show_log()
            self.hgthread = None
            def call_callback():
                callback(returncode, self.useraborted, *args, **kargs)
                self.useraborted = False
            gtklib.idle_add_single_call(call_callback)
            return False # Stop polling this function
        else:
            return True # Continue polling
示例#29
0
 def newfolder_notify(newfolder):
     curpath = entry.get_text()
     newpath = os.path.join(curpath, newfolder)
     newpath = hglib.toutf(os.path.abspath(newpath))
     root = paths.find_root(newpath)
     if root:
         self.set_title(root + " - " + _("browser"))
     else:
         self.set_title(_("browser"))
     entry.set_text(newpath)
     browse.chdir(newpath)
示例#30
0
    def __init__(self, repos=[]):
        gdialog.GDialog.__init__(self, norepo=True)

        srcpath = hglib.toutf(os.getcwd())
        destpath = srcpath
        if len(repos) > 1:
            srcpath = repos[0]
            destpath = repos[1]
        elif len(repos):
            srcpath = repos[0]
        self.srcpath = srcpath
        self.destpath = destpath
示例#31
0
def get_files_from_listfile():
    global _lines
    global _linesutf8
    lines = []
    need_to_utf8 = False
    if os.name == 'nt':
        try:
            fixutf8 = extensions.find("fixutf8")
            if fixutf8:
                need_to_utf8 = True
        except KeyError:
            pass

    if need_to_utf8:
        lines += _linesutf8
        for l in _lines:
            lines.append(hglib.toutf(l))
    else:
        lines += _lines
        for l in _linesutf8:
            lines.append(hglib.fromutf(l))

    # Convert absolute file paths to repo/cwd canonical
    cwd = os.getcwd()
    root = paths.find_root(cwd)
    if not root:
        return lines
    if cwd == root:
        cwd_rel = ''
    else:
        cwd_rel = cwd[len(root + os.sep):] + os.sep
    files = []
    for f in lines:
        try:
            cpath = scmutil.canonpath(root, cwd, f)
            # canonpath will abort on .hg/ paths
        except util.Abort:
            continue
        if cpath.startswith(cwd_rel):
            cpath = cpath[len(cwd_rel):]
            files.append(cpath)
        else:
            files.append(f)
    return files
示例#32
0
def test_toutf_fallback():
    assert_equals(JAPANESE_KANA_I.encode('utf-8'),
                  hglib.toutf(JAPANESE_KANA_I.encode('euc-jp')))
示例#33
0
def test_lossless_utf_cannot_roundtrip():
    u = JAPANESE_KANA_I.encode('cp932')  # bad encoding
    l = hglib.fromutf(u)
    assert_not_equals(u, hglib.toutf(l))
示例#34
0
def test_lossless_utf_replaced():
    u = JAPANESE_KANA_I.encode('utf-8')
    l = hglib.fromutf(u)
    assert_equals('?', l)
    assert_equals(u, hglib.toutf(l))