File: cfgactions.py

package info (click to toggle)
git-cola 4.14.0-1
  • links: PTS
  • area: main
  • in suites: forky, sid
  • size: 6,812 kB
  • sloc: python: 37,625; sh: 298; makefile: 223; xml: 102; tcl: 62
file content (339 lines) | stat: -rw-r--r-- 10,670 bytes parent folder | download | duplicates (2)
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
import os

from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt

from .. import core
from .. import gitcmds
from .. import icons
from .. import qtutils
from ..i18n import N_
from ..interaction import Interaction
from . import defs
from . import completion
from . import standard
from .text import LineEdit


def install():
    Interaction.run_command = staticmethod(run_command)
    Interaction.confirm_config_action = staticmethod(confirm_config_action)


def get_config_actions(context):
    cfg = context.cfg
    return cfg.get_guitool_names_and_shortcuts()


def confirm_config_action(context, name, opts):
    dlg = ActionDialog(context, qtutils.active_window(), name, opts)
    dlg.show()
    if dlg.exec_() != QtWidgets.QDialog.Accepted:
        return False
    rev = dlg.revision()
    if rev:
        opts['revision'] = rev
    args = dlg.args()
    if args:
        opts['args'] = args
    return True


def run_command(title, command):
    """Show a command widget"""
    view = GitCommandWidget(title, qtutils.active_window())
    view.set_command(command)
    view.show()
    view.raise_()
    view.run()
    view.exec_()
    return (view.exitstatus, view.out, view.err)


class GitCommandWidget(standard.Dialog):
    """Text viewer that reads the output of a command synchronously"""

    # Keep us in scope otherwise PyQt kills the widget
    def __init__(self, title, parent=None):
        standard.Dialog.__init__(self, parent)
        self.setWindowTitle(title)
        if parent is not None:
            self.setWindowModality(Qt.ApplicationModal)

        # Construct the process
        self.proc = QtCore.QProcess(self)
        self.exitstatus = 0
        self.out = ''
        self.err = ''
        self.command = []

        # Create the text browser
        self.output_text = QtWidgets.QTextBrowser(self)
        self.output_text.setAcceptDrops(False)
        self.output_text.setTabChangesFocus(True)
        self.output_text.setUndoRedoEnabled(False)
        self.output_text.setReadOnly(True)
        self.output_text.setAcceptRichText(False)

        # Create abort / close buttons
        # Start with abort disabled - will be enabled when the process is run.
        self.button_abort = qtutils.create_button(text=N_('Abort'), enabled=False)
        self.button_close = qtutils.close_button()

        # Put them in a horizontal layout at the bottom.
        self.button_box = QtWidgets.QDialogButtonBox(self)
        self.button_box.addButton(
            self.button_abort, QtWidgets.QDialogButtonBox.RejectRole
        )
        self.button_box.addButton(
            self.button_close, QtWidgets.QDialogButtonBox.AcceptRole
        )

        # Connect the signals to the process
        self.proc.readyReadStandardOutput.connect(self.read_stdout)
        self.proc.readyReadStandardError.connect(self.read_stderr)
        self.proc.finished.connect(self.proc_finished)
        self.proc.stateChanged.connect(self.proc_state_changed)

        qtutils.connect_button(self.button_abort, self.abort)
        qtutils.connect_button(self.button_close, self.close)

        self._layout = qtutils.vbox(
            defs.margin, defs.spacing, self.output_text, self.button_box
        )
        self.setLayout(self._layout)

        self.resize(720, 420)

    def set_command(self, command):
        self.command = command

    def run(self):
        """Runs the process"""
        self.proc.start(self.command[0], self.command[1:])

    def read_stdout(self):
        text = self.read_stream(self.proc.readAllStandardOutput)
        self.out += text

    def read_stderr(self):
        text = self.read_stream(self.proc.readAllStandardError)
        self.err += text

    def read_stream(self, func):
        data = func().data()
        text = core.decode(data)
        self.append_text(text)
        return text

    def append_text(self, text):
        cursor = self.output_text.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(text)
        cursor.movePosition(cursor.End)
        self.output_text.setTextCursor(cursor)

    def abort(self):
        if self.proc.state() != QtCore.QProcess.NotRunning:
            # Terminate seems to do nothing in windows
            self.proc.terminate()
            # Kill the process.
            QtCore.QTimer.singleShot(1000, self.proc.kill)

    def closeEvent(self, event):
        if self.proc.state() != QtCore.QProcess.NotRunning:
            # The process is still running, make sure we really want to abort.
            title = N_('Abort Action')
            msg = N_(
                'An action is still running.\n'
                'Terminating it could result in data loss.'
            )
            info_text = N_('Abort the action?')
            ok_text = N_('Abort Action')
            if Interaction.confirm(
                title, msg, info_text, ok_text, default=False, icon=icons.close()
            ):
                self.abort()
                event.accept()
            else:
                event.ignore()
        else:
            event.accept()

        return standard.Dialog.closeEvent(self, event)

    def proc_state_changed(self, newstate):
        # State of process has changed - change the abort button state.
        if newstate == QtCore.QProcess.NotRunning:
            self.button_abort.setEnabled(False)
        else:
            self.button_abort.setEnabled(True)

    def proc_finished(self, status):
        self.exitstatus = status


class ActionDialog(standard.Dialog):
    VALUES = {}

    def __init__(self, context, parent, name, opts):
        standard.Dialog.__init__(self, parent)
        self.context = context
        self.action_name = name
        self.opts = opts

        try:
            values = self.VALUES[name]
        except KeyError:
            values = self.VALUES[name] = {}

        self.setWindowModality(Qt.ApplicationModal)

        title = opts.get('title')
        if title:
            self.setWindowTitle(os.path.expandvars(title))

        self.prompt = QtWidgets.QLabel()
        prompt = opts.get('prompt')
        if prompt:
            self.prompt.setText(os.path.expandvars(prompt))

        self.argslabel = QtWidgets.QLabel()
        if 'argprompt' not in opts or opts.get('argprompt') is True:
            argprompt = N_('Arguments')
        else:
            argprompt = opts.get('argprompt')
        self.argslabel.setText(argprompt)

        self.argstxt = LineEdit()
        if self.opts.get('argprompt'):
            try:
                # Remember the previous value
                saved_value = values['argstxt']
                self.argstxt.setText(saved_value)
            except KeyError:
                pass
        else:
            self.argslabel.setMinimumSize(10, 10)
            self.argstxt.setMinimumSize(10, 10)
            self.argstxt.hide()
            self.argslabel.hide()

        revs = (
            (N_('Local Branch'), gitcmds.branch_list(context, remote=False)),
            (N_('Tracking Branch'), gitcmds.branch_list(context, remote=True)),
            (N_('Tag'), gitcmds.tag_list(context)),
        )

        if 'revprompt' not in opts or opts.get('revprompt') is True:
            revprompt = N_('Revision')
        else:
            revprompt = opts.get('revprompt')
        self.revselect = RevisionSelector(context, self, revs)
        self.revselect.set_revision_label(revprompt)

        if not opts.get('revprompt'):
            self.revselect.hide()

        # Close/Run buttons
        self.closebtn = qtutils.close_button()
        self.runbtn = qtutils.create_button(
            text=N_('Run'), default=True, icon=icons.ok()
        )

        self.argslayt = qtutils.hbox(
            defs.margin, defs.spacing, self.argslabel, self.argstxt
        )

        self.btnlayt = qtutils.hbox(
            defs.margin, defs.spacing, qtutils.STRETCH, self.closebtn, self.runbtn
        )

        self.layt = qtutils.vbox(
            defs.margin,
            defs.spacing,
            self.prompt,
            self.argslayt,
            self.revselect,
            self.btnlayt,
        )
        self.setLayout(self.layt)

        self.argstxt.textChanged.connect(self._argstxt_changed)
        qtutils.connect_button(self.closebtn, self.reject)
        qtutils.connect_button(self.runbtn, self.accept)

        # Widen the dialog by default
        self.resize(666, self.height())

    def revision(self):
        return self.revselect.revision()

    def args(self):
        return self.argstxt.text()

    def _argstxt_changed(self, value):
        """Store the argstxt value so that we can remember it between calls"""
        self.VALUES[self.action_name]['argstxt'] = value


class RevisionSelector(QtWidgets.QWidget):
    def __init__(self, context, parent, revs):
        QtWidgets.QWidget.__init__(self, parent)

        self.context = context
        self._revs = revs
        self._revdict = dict(revs)

        self._rev_label = QtWidgets.QLabel(self)
        self._revision = completion.GitRefLineEdit(context, parent=self)

        # Create the radio buttons
        radio_btns = []
        self._radio_btns = {}
        for label, rev_list in self._revs:
            radio = qtutils.radio(text=label)
            radio.setObjectName(label)
            qtutils.connect_button(radio, self._set_revision_list)
            radio_btns.append(radio)
            self._radio_btns[label] = radio
        radio_btns.append(qtutils.STRETCH)

        self._rev_list = QtWidgets.QListWidget()
        label, rev_list = self._revs[0]
        self._radio_btns[label].setChecked(True)
        qtutils.set_items(self._rev_list, rev_list)

        self._rev_layt = qtutils.hbox(
            defs.no_margin, defs.spacing, self._rev_label, self._revision
        )

        self._radio_layt = qtutils.hbox(defs.margin, defs.spacing, *radio_btns)

        self._layt = qtutils.vbox(
            defs.no_margin,
            defs.spacing,
            self._rev_layt,
            self._radio_layt,
            self._rev_list,
        )
        self.setLayout(self._layt)
        self._rev_list.itemSelectionChanged.connect(self.selection_changed)

    def revision(self):
        return self._revision.text()

    def set_revision_label(self, txt):
        self._rev_label.setText(txt)

    def _set_revision_list(self):
        sender = self.sender().objectName()
        revs = self._revdict[sender]
        qtutils.set_items(self._rev_list, revs)

    def selection_changed(self):
        items = self._rev_list.selectedItems()
        if not items:
            return
        self._revision.setText(items[0].text())