Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: 

 

# Copyright 2016-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> 

# 

# This file is part of qutebrowser. 

# 

# qutebrowser is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# qutebrowser is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. 

 

"""Showing prompts above the statusbar.""" 

 

import os.path 

import html 

import collections 

 

import attr 

import sip 

from PyQt5.QtCore import (pyqtSlot, pyqtSignal, Qt, QTimer, QDir, QModelIndex, 

QItemSelectionModel, QObject, QEventLoop) 

from PyQt5.QtWidgets import (QWidget, QGridLayout, QVBoxLayout, QLineEdit, 

QLabel, QFileSystemModel, QTreeView, QSizePolicy, 

QSpacerItem) 

 

from qutebrowser.browser import downloads 

from qutebrowser.config import config 

from qutebrowser.utils import usertypes, log, utils, qtutils, objreg, message 

from qutebrowser.keyinput import modeman 

from qutebrowser.commands import cmdutils, cmdexc 

 

 

prompt_queue = None 

 

 

@attr.s 

class AuthInfo: 

 

"""Authentication info returned by a prompt.""" 

 

user = attr.ib() 

password = attr.ib() 

 

 

class Error(Exception): 

 

"""Base class for errors in this module.""" 

 

 

class UnsupportedOperationError(Exception): 

 

"""Raised when the prompt class doesn't support the requested operation.""" 

 

 

class PromptQueue(QObject): 

 

"""Global manager and queue for upcoming prompts. 

 

The way in which multiple questions are handled deserves some explanation. 

 

If a question is blocking, we *need* to ask it immediately, and can't wait 

for previous questions to finish. We could theoretically ask a blocking 

question inside of another blocking one, so in ask_question we simply save 

the current question on the stack, let the user answer the *most recent* 

question, and then restore the previous state. 

 

With a non-blocking question, things are a bit easier. We simply add it to 

self._queue if we're still busy handling another question, since it can be 

answered at any time. 

 

In either case, as soon as we finished handling a question, we call 

_pop_later() which schedules a _pop to ask the next question in _queue. We 

schedule it rather than doing it immediately because then the order of how 

things happen is clear, e.g. on_mode_left can't happen after we already set 

up the *new* question. 

 

Attributes: 

_shutting_down: Whether we're currently shutting down the prompter and 

should ignore future questions to avoid segfaults. 

_loops: A list of local EventLoops to spin in when blocking. 

_queue: A deque of waiting questions. 

_question: The current Question object if we're handling a question. 

 

Signals: 

show_prompts: Emitted with a Question object when prompts should be 

shown. 

""" 

 

show_prompts = pyqtSignal(usertypes.Question) 

 

def __init__(self, parent=None): 

super().__init__(parent) 

self._question = None 

self._shutting_down = False 

self._loops = [] 

self._queue = collections.deque() 

message.global_bridge.mode_left.connect(self._on_mode_left) 

 

def __repr__(self): 

return utils.get_repr(self, loops=len(self._loops), 

queue=len(self._queue), question=self._question) 

 

def _pop_later(self): 

"""Helper to call self._pop as soon as everything else is done.""" 

QTimer.singleShot(0, self._pop) 

 

def _pop(self): 

"""Pop a question from the queue and ask it, if there are any.""" 

log.prompt.debug("Popping from queue {}".format(self._queue)) 

if self._queue: 

question = self._queue.popleft() 

if not sip.isdeleted(question): 

# the question could already be deleted, e.g. by a cancelled 

# download. See 

# https://github.com/qutebrowser/qutebrowser/issues/415 

self.ask_question(question, blocking=False) 

 

def shutdown(self): 

"""Cancel all blocking questions. 

 

Quits and removes all running event loops. 

 

Return: 

True if loops needed to be aborted, 

False otherwise. 

""" 

log.prompt.debug("Shutting down with loops {}".format(self._loops)) 

self._shutting_down = True 

if self._loops: 

for loop in self._loops: 

loop.quit() 

loop.deleteLater() 

return True 

else: 

return False 

 

@pyqtSlot(usertypes.Question, bool) 

def ask_question(self, question, blocking): 

"""Display a prompt for a given question. 

 

Args: 

question: The Question object to ask. 

blocking: If True, this function blocks and returns the result. 

 

Return: 

The answer of the user when blocking=True. 

None if blocking=False. 

""" 

log.prompt.debug("Asking question {}, blocking {}, loops {}, queue " 

"{}".format(question, blocking, self._loops, 

self._queue)) 

 

if self._shutting_down: 

# If we're currently shutting down we have to ignore this question 

# to avoid segfaults - see 

# https://github.com/qutebrowser/qutebrowser/issues/95 

log.prompt.debug("Ignoring question because we're shutting down.") 

question.abort() 

return None 

 

if self._question is not None and not blocking: 

# We got an async question, but we're already busy with one, so we 

# just queue it up for later. 

log.prompt.debug("Adding {} to queue.".format(question)) 

self._queue.append(question) 

return None 

 

if blocking: 

# If we're blocking we save the old question on the stack, so we 

# can restore it after exec, if exec gets called multiple times. 

log.prompt.debug("New question is blocking, saving {}".format( 

self._question)) 

old_question = self._question 

if old_question is not None: 

old_question.interrupted = True 

 

self._question = question 

self.show_prompts.emit(question) 

 

if blocking: 

loop = qtutils.EventLoop() 

self._loops.append(loop) 

loop.destroyed.connect(lambda: self._loops.remove(loop)) 

question.completed.connect(loop.quit) 

question.completed.connect(loop.deleteLater) 

log.prompt.debug("Starting loop.exec_() for {}".format(question)) 

loop.exec_(QEventLoop.ExcludeSocketNotifiers) 

log.prompt.debug("Ending loop.exec_() for {}".format(question)) 

 

log.prompt.debug("Restoring old question {}".format(old_question)) 

self._question = old_question 

self.show_prompts.emit(old_question) 

if old_question is None: 

# Nothing left to restore, so we can go back to popping async 

# questions. 

if self._queue: 

self._pop_later() 

 

return question.answer 

else: 

question.completed.connect(self._pop_later) 

return None 

 

@pyqtSlot(usertypes.KeyMode) 

def _on_mode_left(self, mode): 

"""Abort question when a prompt mode was left.""" 

if mode not in [usertypes.KeyMode.prompt, usertypes.KeyMode.yesno]: 

return 

if self._question is None: 

return 

 

log.prompt.debug("Left mode {}, hiding {}".format( 

mode, self._question)) 

self.show_prompts.emit(None) 

if self._question.answer is None and not self._question.is_aborted: 

log.prompt.debug("Cancelling {} because {} was left".format( 

self._question, mode)) 

self._question.cancel() 

self._question = None 

 

 

class PromptContainer(QWidget): 

 

"""Container for prompts to be shown above the statusbar. 

 

This is a per-window object, however each window shows the same prompt. 

 

Attributes: 

_layout: The layout used to show prompts in. 

_win_id: The window ID this object is associated with. 

 

Signals: 

update_geometry: Emitted when the geometry should be updated. 

""" 

 

STYLESHEET = """ 

QWidget#PromptContainer { 

{% if conf.statusbar.position == 'top' %} 

border-bottom-left-radius: {{ conf.prompt.radius }}px; 

border-bottom-right-radius: {{ conf.prompt.radius }}px; 

{% else %} 

border-top-left-radius: {{ conf.prompt.radius }}px; 

border-top-right-radius: {{ conf.prompt.radius }}px; 

{% endif %} 

} 

 

QWidget { 

font: {{ conf.fonts.prompts }}; 

color: {{ conf.colors.prompts.fg }}; 

background-color: {{ conf.colors.prompts.bg }}; 

} 

 

QLineEdit { 

border: {{ conf.colors.prompts.border }}; 

} 

 

QTreeView { 

selection-background-color: {{ conf.colors.prompts.selected.bg }}; 

border: {{ conf.colors.prompts.border }}; 

} 

 

QTreeView::branch { 

background-color: {{ conf.colors.prompts.bg }}; 

} 

 

QTreeView::item:selected, QTreeView::item:selected:hover, 

QTreeView::branch:selected { 

background-color: {{ conf.colors.prompts.selected.bg }}; 

} 

""" 

update_geometry = pyqtSignal() 

 

def __init__(self, win_id, parent=None): 

super().__init__(parent) 

self._layout = QVBoxLayout(self) 

self._layout.setContentsMargins(10, 10, 10, 10) 

self._win_id = win_id 

self._prompt = None 

 

self.setObjectName('PromptContainer') 

self.setAttribute(Qt.WA_StyledBackground, True) 

config.set_register_stylesheet(self) 

 

message.global_bridge.prompt_done.connect(self._on_prompt_done) 

prompt_queue.show_prompts.connect(self._on_show_prompts) 

message.global_bridge.mode_left.connect(self._on_global_mode_left) 

 

def __repr__(self): 

return utils.get_repr(self, win_id=self._win_id) 

 

@pyqtSlot(usertypes.Question) 

def _on_show_prompts(self, question): 

"""Show a prompt for the given question. 

 

Args: 

question: A Question object or None. 

""" 

item = self._layout.takeAt(0) 

if item is not None: 

widget = item.widget() 

log.prompt.debug("Deleting old prompt {}".format(widget)) 

widget.hide() 

widget.deleteLater() 

 

if question is None: 

log.prompt.debug("No prompts left, hiding prompt container.") 

self._prompt = None 

self.hide() 

return 

 

classes = { 

usertypes.PromptMode.yesno: YesNoPrompt, 

usertypes.PromptMode.text: LineEditPrompt, 

usertypes.PromptMode.user_pwd: AuthenticationPrompt, 

usertypes.PromptMode.download: DownloadFilenamePrompt, 

usertypes.PromptMode.alert: AlertPrompt, 

} 

klass = classes[question.mode] 

prompt = klass(question) 

 

log.prompt.debug("Displaying prompt {}".format(prompt)) 

self._prompt = prompt 

 

if not question.interrupted: 

# If this question was interrupted, we already connected the signal 

question.aborted.connect( 

lambda: modeman.leave(self._win_id, prompt.KEY_MODE, 'aborted', 

maybe=True)) 

modeman.enter(self._win_id, prompt.KEY_MODE, 'question asked') 

 

self.setSizePolicy(prompt.sizePolicy()) 

self._layout.addWidget(prompt) 

prompt.show() 

self.show() 

prompt.setFocus() 

self.update_geometry.emit() 

 

@pyqtSlot(usertypes.KeyMode) 

def _on_prompt_done(self, key_mode): 

"""Leave the prompt mode in this window if a question was answered.""" 

modeman.leave(self._win_id, key_mode, ':prompt-accept', maybe=True) 

 

@pyqtSlot(usertypes.KeyMode) 

def _on_global_mode_left(self, mode): 

"""Leave prompt/yesno mode in this window if it was left elsewhere. 

 

This ensures no matter where a prompt was answered, we leave the prompt 

mode and dispose of the prompt object in every window. 

""" 

if mode not in [usertypes.KeyMode.prompt, usertypes.KeyMode.yesno]: 

return 

modeman.leave(self._win_id, mode, 'left in other window', maybe=True) 

item = self._layout.takeAt(0) 

if item is not None: 

widget = item.widget() 

log.prompt.debug("Deleting prompt {}".format(widget)) 

widget.hide() 

widget.deleteLater() 

 

@cmdutils.register(instance='prompt-container', scope='window', 

modes=[usertypes.KeyMode.prompt, 

usertypes.KeyMode.yesno]) 

def prompt_accept(self, value=None): 

"""Accept the current prompt. 

 

// 

 

This executes the next action depending on the question mode, e.g. asks 

for the password or leaves the mode. 

 

Args: 

value: If given, uses this value instead of the entered one. 

For boolean prompts, "yes"/"no" are accepted as value. 

""" 

question = self._prompt.question 

try: 

done = self._prompt.accept(value) 

except Error as e: 

raise cmdexc.CommandError(str(e)) 

if done: 

message.global_bridge.prompt_done.emit(self._prompt.KEY_MODE) 

question.done() 

 

@cmdutils.register(instance='prompt-container', scope='window', 

modes=[usertypes.KeyMode.prompt], maxsplit=0) 

def prompt_open_download(self, cmdline: str = None): 

"""Immediately open a download. 

 

If no specific command is given, this will use the system's default 

application to open the file. 

 

Args: 

cmdline: The command which should be used to open the file. A `{}` 

is expanded to the temporary file name. If no `{}` is 

present, the filename is automatically appended to the 

cmdline. 

""" 

try: 

self._prompt.download_open(cmdline) 

except UnsupportedOperationError: 

pass 

 

@cmdutils.register(instance='prompt-container', scope='window', 

modes=[usertypes.KeyMode.prompt]) 

@cmdutils.argument('which', choices=['next', 'prev']) 

def prompt_item_focus(self, which): 

"""Shift the focus of the prompt file completion menu to another item. 

 

Args: 

which: 'next', 'prev' 

""" 

try: 

self._prompt.item_focus(which) 

except UnsupportedOperationError: 

pass 

 

@cmdutils.register( 

instance='prompt-container', scope='window', 

modes=[usertypes.KeyMode.prompt, usertypes.KeyMode.yesno]) 

def prompt_yank(self, sel=False): 

"""Yank URL to clipboard or primary selection. 

 

Args: 

sel: Use the primary selection instead of the clipboard. 

""" 

question = self._prompt.question 

if question.url is None: 

message.error('No URL found.') 

return 

if sel and utils.supports_selection(): 

target = 'primary selection' 

else: 

sel = False 

target = 'clipboard' 

utils.set_clipboard(question.url, sel) 

message.info("Yanked to {}: {}".format(target, question.url)) 

 

 

class LineEdit(QLineEdit): 

 

"""A line edit used in prompts.""" 

 

def __init__(self, parent=None): 

super().__init__(parent) 

self.setStyleSheet(""" 

QLineEdit { 

background-color: transparent; 

} 

""") 

self.setAttribute(Qt.WA_MacShowFocusRect, False) 

 

def keyPressEvent(self, e): 

"""Override keyPressEvent to paste primary selection on Shift + Ins.""" 

462 ↛ 463line 462 didn't jump to line 463, because the condition on line 462 was never true if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier: 

try: 

text = utils.get_clipboard(selection=True, fallback=True) 

except utils.ClipboardError: # pragma: no cover 

e.ignore() 

else: 

e.accept() 

self.insert(text) 

return 

super().keyPressEvent(e) 

 

def __repr__(self): 

return utils.get_repr(self) 

 

 

class _BasePrompt(QWidget): 

 

"""Base class for all prompts.""" 

 

KEY_MODE = usertypes.KeyMode.prompt 

 

def __init__(self, question, parent=None): 

super().__init__(parent) 

self.question = question 

self._vbox = QVBoxLayout(self) 

self._vbox.setSpacing(15) 

self._key_grid = None 

 

def __repr__(self): 

return utils.get_repr(self, question=self.question, constructor=True) 

 

def _init_texts(self, question): 

assert question.title is not None, question 

title = '<font size="4"><b>{}</b></font>'.format( 

html.escape(question.title)) 

title_label = QLabel(title, self) 

self._vbox.addWidget(title_label) 

499 ↛ 501line 499 didn't jump to line 501, because the condition on line 499 was never true if question.text is not None: 

# Not doing any HTML escaping here as the text can be formatted 

text_label = QLabel(question.text) 

text_label.setTextInteractionFlags(Qt.TextSelectableByMouse) 

self._vbox.addWidget(text_label) 

 

def _init_key_label(self): 

assert self._key_grid is None, self._key_grid 

self._key_grid = QGridLayout() 

self._key_grid.setVerticalSpacing(0) 

 

# The bindings are all in the 'prompt' mode, even for yesno prompts 

all_bindings = config.key_instance.get_reverse_bindings_for('prompt') 

labels = [] 

 

for cmd, text in self._allowed_commands(): 

bindings = all_bindings.get(cmd, []) 

516 ↛ 517line 516 didn't jump to line 517, because the condition on line 516 was never true if bindings: 

binding = None 

preferred = ['<enter>', '<escape>'] 

for pref in preferred: 

if pref in bindings: 

binding = pref 

if binding is None: 

binding = bindings[0] 

key_label = QLabel('<b>{}</b>'.format(html.escape(binding))) 

text_label = QLabel(text) 

labels.append((key_label, text_label)) 

 

528 ↛ 529line 528 didn't jump to line 529, because the loop on line 528 never started for i, (key_label, text_label) in enumerate(labels): 

self._key_grid.addWidget(key_label, i, 0) 

self._key_grid.addWidget(text_label, i, 1) 

 

spacer = QSpacerItem(0, 0, QSizePolicy.Expanding) 

self._key_grid.addItem(spacer, 0, 2) 

 

self._vbox.addLayout(self._key_grid) 

 

def accept(self, value=None): 

raise NotImplementedError 

 

def download_open(self, _cmdline): 

"""Open the download directly if this is a download prompt.""" 

raise UnsupportedOperationError 

 

def item_focus(self, _which): 

"""Switch to next file item if this is a filename prompt..""" 

raise UnsupportedOperationError 

 

def _allowed_commands(self): 

"""Get the commands we could run as response to this message.""" 

raise NotImplementedError 

 

 

class LineEditPrompt(_BasePrompt): 

 

"""A prompt for a single text value.""" 

 

def __init__(self, question, parent=None): 

super().__init__(question, parent) 

self._lineedit = LineEdit(self) 

self._init_texts(question) 

self._vbox.addWidget(self._lineedit) 

if question.default: 

self._lineedit.setText(question.default) 

self.setFocusProxy(self._lineedit) 

self._init_key_label() 

 

def accept(self, value=None): 

text = value if value is not None else self._lineedit.text() 

self.question.answer = text 

return True 

 

def _allowed_commands(self): 

return [('prompt-accept', 'Accept'), ('leave-mode', 'Abort')] 

 

 

class FilenamePrompt(_BasePrompt): 

 

"""A prompt for a filename.""" 

 

def __init__(self, question, parent=None): 

super().__init__(question, parent) 

self._init_texts(question) 

self._init_key_label() 

 

self._lineedit = LineEdit(self) 

586 ↛ 588line 586 didn't jump to line 588, because the condition on line 586 was never false if question.default: 

self._lineedit.setText(question.default) 

self._lineedit.textEdited.connect(self._set_fileview_root) 

self._vbox.addWidget(self._lineedit) 

 

self.setFocusProxy(self._lineedit) 

 

self._init_fileview() 

self._set_fileview_root(question.default) 

 

596 ↛ exitline 596 didn't return from function '__init__', because the condition on line 596 was never false if config.val.prompt.filebrowser: 

self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) 

 

@pyqtSlot(str) 

def _set_fileview_root(self, path, *, tabbed=False): 

"""Set the root path for the file display.""" 

separators = os.sep 

603 ↛ 604line 603 didn't jump to line 604, because the condition on line 603 was never true if os.altsep is not None: 

separators += os.altsep 

 

dirname = os.path.dirname(path) 

 

try: 

609 ↛ 610line 609 didn't jump to line 610, because the condition on line 609 was never true if not path: 

pass 

611 ↛ 613line 611 didn't jump to line 613, because the condition on line 611 was never true elif path in separators and os.path.isdir(path): 

# Input "/" -> don't strip anything 

pass 

elif path[-1] in separators and os.path.isdir(path): 

# Input like /foo/bar/ -> show /foo/bar/ contents 

path = path.rstrip(separators) 

elif os.path.isdir(dirname) and not tabbed: 

# Input like /foo/ba -> show /foo contents 

path = dirname 

else: 

return 

except OSError: 

log.prompt.exception("Failed to get directory information") 

return 

 

root = self._file_model.setRootPath(path) 

self._file_view.setRootIndex(root) 

 

@pyqtSlot(QModelIndex) 

def _insert_path(self, index, *, clicked=True): 

"""Handle an element selection. 

 

Args: 

index: The QModelIndex of the selected element. 

clicked: Whether the element was clicked. 

""" 

path = os.path.normpath(self._file_model.filePath(index)) 

638 ↛ 639line 638 didn't jump to line 639, because the condition on line 638 was never true if clicked: 

path += os.sep 

else: 

# On Windows, when we have C:\foo and tab over .., we get C:\ 

path = path.rstrip(os.sep) 

 

log.prompt.debug('Inserting path {}'.format(path)) 

self._lineedit.setText(path) 

self._lineedit.setFocus() 

self._set_fileview_root(path, tabbed=True) 

648 ↛ 650line 648 didn't jump to line 650, because the condition on line 648 was never true if clicked: 

# Avoid having a ..-subtree highlighted 

self._file_view.setCurrentIndex(QModelIndex()) 

 

def _init_fileview(self): 

self._file_view = QTreeView(self) 

self._file_model = QFileSystemModel(self) 

self._file_view.setModel(self._file_model) 

self._file_view.clicked.connect(self._insert_path) 

 

658 ↛ 661line 658 didn't jump to line 661, because the condition on line 658 was never false if config.val.prompt.filebrowser: 

self._vbox.addWidget(self._file_view) 

else: 

self._file_view.hide() 

 

# Only show name 

self._file_view.setHeaderHidden(True) 

for col in range(1, 4): 

self._file_view.setColumnHidden(col, True) 

# Nothing selected initially 

self._file_view.setCurrentIndex(QModelIndex()) 

# The model needs to be sorted so we get the correct first/last index 

self._file_model.directoryLoaded.connect( 

lambda: self._file_model.sort(0)) 

 

def accept(self, value=None): 

text = value if value is not None else self._lineedit.text() 

text = downloads.transform_path(text) 

if text is None: 

message.error("Invalid filename") 

return False 

self.question.answer = text 

return True 

 

def item_focus(self, which): 

# This duplicates some completion code, but I don't see a nicer way... 

assert which in ['prev', 'next'], which 

selmodel = self._file_view.selectionModel() 

 

parent = self._file_view.rootIndex() 

first_index = self._file_model.index(0, 0, parent) 

row = self._file_model.rowCount(parent) - 1 

last_index = self._file_model.index(row, 0, parent) 

 

692 ↛ 694line 692 didn't jump to line 694, because the condition on line 692 was never true if not first_index.isValid(): 

# No entries 

return 

 

assert last_index.isValid() 

 

idx = selmodel.currentIndex() 

if not idx.isValid(): 

# No item selected yet 

idx = last_index if which == 'prev' else first_index 

elif which == 'prev': 

idx = self._file_view.indexAbove(idx) 

else: 

assert which == 'next', which 

idx = self._file_view.indexBelow(idx) 

 

# wrap around if we arrived at beginning/end 

709 ↛ 710line 709 didn't jump to line 710, because the condition on line 709 was never true if not idx.isValid(): 

idx = last_index if which == 'prev' else first_index 

 

selmodel.setCurrentIndex( 

idx, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) 

self._insert_path(idx, clicked=False) 

 

def _allowed_commands(self): 

return [('prompt-accept', 'Accept'), ('leave-mode', 'Abort')] 

 

 

class DownloadFilenamePrompt(FilenamePrompt): 

 

"""A prompt for a filename for downloads.""" 

 

def __init__(self, question, parent=None): 

super().__init__(question, parent) 

self._file_model.setFilter(QDir.AllDirs | QDir.Drives | QDir.NoDot) 

 

def accept(self, value=None): 

done = super().accept(value) 

answer = self.question.answer 

if answer is not None: 

self.question.answer = downloads.FileDownloadTarget(answer) 

return done 

 

def download_open(self, cmdline): 

self.question.answer = downloads.OpenFileDownloadTarget(cmdline) 

self.question.done() 

message.global_bridge.prompt_done.emit(self.KEY_MODE) 

 

def _allowed_commands(self): 

cmds = [ 

('prompt-accept', 'Accept'), 

('leave-mode', 'Abort'), 

('prompt-open-download', "Open download"), 

('prompt-yank', "Yank URL"), 

] 

return cmds 

 

 

class AuthenticationPrompt(_BasePrompt): 

 

"""A prompt for username/password.""" 

 

def __init__(self, question, parent=None): 

super().__init__(question, parent) 

self._init_texts(question) 

 

user_label = QLabel("Username:", self) 

self._user_lineedit = LineEdit(self) 

 

password_label = QLabel("Password:", self) 

self._password_lineedit = LineEdit(self) 

self._password_lineedit.setEchoMode(QLineEdit.Password) 

 

grid = QGridLayout() 

grid.addWidget(user_label, 1, 0) 

grid.addWidget(self._user_lineedit, 1, 1) 

grid.addWidget(password_label, 2, 0) 

grid.addWidget(self._password_lineedit, 2, 1) 

self._vbox.addLayout(grid) 

self._init_key_label() 

 

assert not question.default, question.default 

self.setFocusProxy(self._user_lineedit) 

 

def accept(self, value=None): 

if value is not None: 

if ':' not in value: 

raise Error("Value needs to be in the format " 

"username:password, but {} was given".format( 

value)) 

username, password = value.split(':', maxsplit=1) 

self.question.answer = AuthInfo(username, password) 

return True 

elif self._user_lineedit.hasFocus(): 

# Earlier, tab was bound to :prompt-accept, so to still support 

# that we simply switch the focus when tab was pressed. 

self._password_lineedit.setFocus() 

return False 

else: 

self.question.answer = AuthInfo(self._user_lineedit.text(), 

self._password_lineedit.text()) 

return True 

 

def item_focus(self, which): 

"""Support switching between fields with tab.""" 

assert which in ['prev', 'next'], which 

if which == 'next' and self._user_lineedit.hasFocus(): 

self._password_lineedit.setFocus() 

elif which == 'prev' and self._password_lineedit.hasFocus(): 

self._user_lineedit.setFocus() 

 

def _allowed_commands(self): 

return [('prompt-accept', "Accept"), 

('leave-mode', "Abort")] 

 

 

class YesNoPrompt(_BasePrompt): 

 

"""A prompt with yes/no answers.""" 

 

KEY_MODE = usertypes.KeyMode.yesno 

 

def __init__(self, question, parent=None): 

super().__init__(question, parent) 

self._init_texts(question) 

self._init_key_label() 

 

def accept(self, value=None): 

if value is None: 

if self.question.default is None: 

raise Error("No default value was set for this question!") 

self.question.answer = self.question.default 

elif value == 'yes': 

self.question.answer = True 

elif value == 'no': 

self.question.answer = False 

else: 

raise Error("Invalid value {} - expected yes/no!".format(value)) 

return True 

 

def _allowed_commands(self): 

cmds = [ 

('prompt-accept yes', "Yes"), 

('prompt-accept no', "No"), 

('prompt-yank', "Yank URL"), 

] 

 

if self.question.default is not None: 

assert self.question.default in [True, False] 

default = 'yes' if self.question.default else 'no' 

cmds.append(('prompt-accept', "Use default ({})".format(default))) 

 

cmds.append(('leave-mode', "Abort")) 

return cmds 

 

 

class AlertPrompt(_BasePrompt): 

 

"""A prompt without any answer possibility.""" 

 

def __init__(self, question, parent=None): 

super().__init__(question, parent) 

self._init_texts(question) 

self._init_key_label() 

 

def accept(self, value=None): 

if value is not None: 

raise Error("No value is permitted with alert prompts!") 

# Simply mark prompt as done without setting self.question.answer 

return True 

 

def _allowed_commands(self): 

return [('prompt-accept', "Hide")] 

 

 

def init(): 

"""Initialize global prompt objects.""" 

global prompt_queue 

prompt_queue = PromptQueue() 

objreg.register('prompt-queue', prompt_queue) # for commands 

message.global_bridge.ask_question.connect( 

prompt_queue.ask_question, Qt.DirectConnection)