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

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

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

 

# Copyright 2014-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/>. 

 

"""The tab widget used for TabbedBrowser from browser.py.""" 

 

import functools 

import enum 

 

import attr 

from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Qt, QSize, QRect, QPoint, 

QTimer, QUrl) 

from PyQt5.QtWidgets import (QTabWidget, QTabBar, QSizePolicy, QCommonStyle, 

QStyle, QStylePainter, QStyleOptionTab, 

QStyleFactory, QWidget) 

from PyQt5.QtGui import QIcon, QPalette, QColor 

 

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

from qutebrowser.config import config 

from qutebrowser.misc import objects 

 

 

PixelMetrics = enum.IntEnum('PixelMetrics', ['icon_padding'], 

start=QStyle.PM_CustomBase) 

 

 

class TabWidget(QTabWidget): 

 

"""The tab widget used for TabbedBrowser. 

 

Signals: 

tab_index_changed: Emitted when the current tab was changed. 

arg 0: The index of the tab which is now focused. 

arg 1: The total count of tabs. 

new_tab_requested: Emitted when a new tab is requested. 

""" 

 

tab_index_changed = pyqtSignal(int, int) 

new_tab_requested = pyqtSignal('QUrl', bool, bool) 

 

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

super().__init__(parent) 

bar = TabBar(win_id, self) 

self.setStyle(TabBarStyle()) 

self.setTabBar(bar) 

bar.tabCloseRequested.connect(self.tabCloseRequested) 

bar.tabMoved.connect(functools.partial( 

QTimer.singleShot, 0, self._update_tab_titles)) 

bar.currentChanged.connect(self._on_current_changed) 

bar.new_tab_requested.connect(self._on_new_tab_requested) 

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

self.setDocumentMode(True) 

self.setElideMode(Qt.ElideRight) 

self.setUsesScrollButtons(True) 

bar.setDrawBase(False) 

self._init_config() 

config.instance.changed.connect(self._init_config) 

 

@config.change_filter('tabs') 

def _init_config(self): 

"""Initialize attributes based on the config.""" 

tabbar = self.tabBar() 

self.setMovable(True) 

self.setTabsClosable(False) 

position = config.val.tabs.position 

selection_behavior = config.val.tabs.select_on_remove 

self.setTabPosition(position) 

tabbar.vertical = position in [QTabWidget.West, QTabWidget.East] 

tabbar.setSelectionBehaviorOnRemove(selection_behavior) 

tabbar.refresh() 

 

def set_tab_indicator_color(self, idx, color): 

"""Set the tab indicator color. 

 

Args: 

idx: The tab index. 

color: A QColor. 

""" 

bar = self.tabBar() 

bar.set_tab_data(idx, 'indicator-color', color) 

bar.update(bar.tabRect(idx)) 

 

def set_tab_pinned(self, tab: QWidget, 

pinned: bool) -> None: 

"""Set the tab status as pinned. 

 

Args: 

tab: The tab to pin 

pinned: Pinned tab state to set. 

""" 

bar = self.tabBar() 

idx = self.indexOf(tab) 

 

bar.set_tab_data(idx, 'pinned', pinned) 

tab.data.pinned = pinned 

self._update_tab_title(idx) 

 

def tab_indicator_color(self, idx): 

"""Get the tab indicator color for the given index.""" 

return self.tabBar().tab_indicator_color(idx) 

 

def set_page_title(self, idx, title): 

"""Set the tab title user data.""" 

self.tabBar().set_tab_data(idx, 'page-title', title) 

self._update_tab_title(idx) 

 

def page_title(self, idx): 

"""Get the tab title user data.""" 

return self.tabBar().page_title(idx) 

 

def _update_tab_title(self, idx, field=None): 

"""Update the tab text for the given tab. 

 

Args: 

idx: The tab index to update. 

field: A field name which was updated. If given, the title 

is only set if the given field is in the template. 

""" 

tab = self.widget(idx) 

135 ↛ 136line 135 didn't jump to line 136, because the condition on line 135 was never true if tab.data.pinned: 

fmt = config.val.tabs.title.format_pinned 

else: 

fmt = config.val.tabs.title.format 

 

140 ↛ 142line 140 didn't jump to line 142, because the condition on line 140 was never true if (field is not None and 

(fmt is None or ('{' + field + '}') not in fmt)): 

return 

 

fields = self.get_tab_fields(idx) 

fields['title'] = fields['title'].replace('&', '&&') 

fields['index'] = idx + 1 

 

title = '' if fmt is None else fmt.format(**fields) 

tabbar = self.tabBar() 

 

if tabbar.tabText(idx) != title: 

tabbar.setTabText(idx, title) 

tabbar.setTabToolTip(idx, title) 

 

def get_tab_fields(self, idx): 

"""Get the tab field data.""" 

tab = self.widget(idx) 

158 ↛ 159line 158 didn't jump to line 159, because the condition on line 158 was never true if tab is None: 

log.misc.debug("Got None-tab in get_tab_fields!") 

 

page_title = self.page_title(idx) 

 

fields = {} 

fields['id'] = tab.tab_id 

fields['title'] = page_title 

fields['title_sep'] = ' - ' if page_title else '' 

fields['perc_raw'] = tab.progress() 

fields['backend'] = objects.backend.name 

fields['private'] = ' [Private Mode] ' if tab.private else '' 

 

171 ↛ 172line 171 didn't jump to line 172, because the condition on line 171 was never true if tab.load_status() == usertypes.LoadStatus.loading: 

fields['perc'] = '[{}%] '.format(tab.progress()) 

else: 

fields['perc'] = '' 

 

try: 

url = self.tab_url(idx) 

except qtutils.QtValueError: 

fields['host'] = '' 

fields['current_url'] = '' 

fields['protocol'] = '' 

else: 

fields['host'] = url.host() 

fields['current_url'] = url.toDisplayString() 

fields['protocol'] = url.scheme() 

 

y = tab.scroller.pos_perc()[1] 

188 ↛ 189line 188 didn't jump to line 189, because the condition on line 188 was never true if y is None: 

scroll_pos = '???' 

190 ↛ 192line 190 didn't jump to line 192, because the condition on line 190 was never false elif y <= 0: 

scroll_pos = 'top' 

elif y >= 100: 

scroll_pos = 'bot' 

else: 

scroll_pos = '{:2}%'.format(y) 

 

fields['scroll_pos'] = scroll_pos 

return fields 

 

def _update_tab_titles(self): 

"""Update all texts.""" 

for idx in range(self.count()): 

self._update_tab_title(idx) 

 

def tabInserted(self, idx): 

"""Update titles when a tab was inserted.""" 

super().tabInserted(idx) 

self._update_tab_titles() 

 

def tabRemoved(self, idx): 

"""Update titles when a tab was removed.""" 

super().tabRemoved(idx) 

self._update_tab_titles() 

 

def addTab(self, page, icon_or_text, text_or_empty=None): 

"""Override addTab to use our own text setting logic. 

 

Unfortunately QTabWidget::addTab has these two overloads: 

- QWidget * page, const QIcon & icon, const QString & label 

- QWidget * page, const QString & label 

 

This means we'll get different arguments based on the chosen overload. 

 

Args: 

page: The QWidget to add. 

icon_or_text: Either the QIcon to add or the label. 

text_or_empty: Either the label or None. 

 

Return: 

The index of the newly added tab. 

""" 

if text_or_empty is None: 

icon = None 

text = icon_or_text 

new_idx = super().addTab(page, '') 

else: 

icon = icon_or_text 

text = text_or_empty 

new_idx = super().addTab(page, icon, '') 

self.set_page_title(new_idx, text) 

return new_idx 

 

def insertTab(self, idx, page, icon_or_text, text_or_empty=None): 

"""Override insertTab to use our own text setting logic. 

 

Unfortunately QTabWidget::insertTab has these two overloads: 

- int index, QWidget * page, const QIcon & icon, 

const QString & label 

- int index, QWidget * page, const QString & label 

 

This means we'll get different arguments based on the chosen overload. 

 

Args: 

idx: Where to insert the widget. 

page: The QWidget to add. 

icon_or_text: Either the QIcon to add or the label. 

text_or_empty: Either the label or None. 

 

Return: 

The index of the newly added tab. 

""" 

if text_or_empty is None: 

icon = None 

text = icon_or_text 

new_idx = super().insertTab(idx, page, '') 

else: 

icon = icon_or_text 

text = text_or_empty 

new_idx = super().insertTab(idx, page, icon, '') 

self.set_page_title(new_idx, text) 

return new_idx 

 

@pyqtSlot(int) 

def _on_current_changed(self, index): 

"""Emit the tab_index_changed signal if the current tab changed.""" 

self.tabBar().on_current_changed() 

self.tab_index_changed.emit(index, self.count()) 

 

@pyqtSlot() 

def _on_new_tab_requested(self): 

"""Open a new tab.""" 

self.new_tab_requested.emit(config.val.url.default_page, False, False) 

 

def tab_url(self, idx): 

"""Get the URL of the tab at the given index. 

 

Return: 

The tab URL as QUrl. 

""" 

tab = self.widget(idx) 

291 ↛ 292line 291 didn't jump to line 292, because the condition on line 291 was never true if tab is None: 

url = QUrl() 

else: 

url = tab.url() 

# It's possible for url to be invalid, but the caller will handle that. 

qtutils.ensure_valid(url) 

return url 

 

 

class TabBar(QTabBar): 

 

"""Custom tab bar with our own style. 

 

FIXME: Dragging tabs doesn't look as nice as it does in QTabBar. However, 

fixing this would be a lot of effort, so we'll postpone it until we're 

reimplementing drag&drop for other reasons. 

 

https://github.com/qutebrowser/qutebrowser/issues/126 

 

Attributes: 

vertical: When the tab bar is currently vertical. 

win_id: The window ID this TabBar belongs to. 

 

Signals: 

new_tab_requested: Emitted when a new tab is requested. 

""" 

 

new_tab_requested = pyqtSignal() 

 

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

super().__init__(parent) 

self._win_id = win_id 

self.setStyle(TabBarStyle()) 

self._set_font() 

config.instance.changed.connect(self._on_config_changed) 

self.vertical = False 

self._auto_hide_timer = QTimer() 

self._auto_hide_timer.setSingleShot(True) 

self._auto_hide_timer.timeout.connect(self.maybe_hide) 

self._on_show_switching_delay_changed() 

self.setAutoFillBackground(True) 

self._set_colors() 

QTimer.singleShot(0, self.maybe_hide) 

 

def __repr__(self): 

return utils.get_repr(self, count=self.count()) 

 

def _current_tab(self): 

"""Get the current tab object.""" 

return self.parent().currentWidget() 

 

@pyqtSlot(str) 

def _on_config_changed(self, option: str): 

if option == 'fonts.tabs': 

self._set_font() 

elif option == 'tabs.favicons.scale': 

self._set_icon_size() 

elif option == 'colors.tabs.bar.bg': 

self._set_colors() 

elif option == 'tabs.show_switching_delay': 

self._on_show_switching_delay_changed() 

elif option == 'tabs.show': 

self.maybe_hide() 

 

if option.startswith('colors.tabs.'): 

self.update() 

 

# Clear _minimum_tab_size_hint_helper cache when appropriate 

if option in ["tabs.indicator.padding", 

"tabs.padding", 

"tabs.indicator.width"]: 

self._minimum_tab_size_hint_helper.cache_clear() 

 

def _on_show_switching_delay_changed(self): 

"""Set timer interval when tabs.show_switching_delay got changed.""" 

self._auto_hide_timer.setInterval(config.val.tabs.show_switching_delay) 

 

def on_current_changed(self): 

"""Show tab bar when current tab got changed.""" 

self.maybe_hide() # for fullscreen tabs 

371 ↛ 372line 371 didn't jump to line 372, because the condition on line 371 was never true if config.val.tabs.show == 'switching': 

self.show() 

self._auto_hide_timer.start() 

 

@pyqtSlot() 

def maybe_hide(self): 

"""Hide the tab bar if needed.""" 

show = config.val.tabs.show 

tab = self._current_tab() 

380 ↛ 383line 380 didn't jump to line 383, because the condition on line 380 was never true if (show in ['never', 'switching'] or 

(show == 'multiple' and self.count() == 1) or 

(tab and tab.data.fullscreen)): 

self.hide() 

else: 

self.show() 

 

def set_tab_data(self, idx, key, value): 

"""Set tab data as a dictionary.""" 

389 ↛ 390line 389 didn't jump to line 390, because the condition on line 389 was never true if not 0 <= idx < self.count(): 

raise IndexError("Tab index ({}) out of range ({})!".format( 

idx, self.count())) 

data = self.tabData(idx) 

393 ↛ 395line 393 didn't jump to line 395, because the condition on line 393 was never false if data is None: 

data = {} 

data[key] = value 

self.setTabData(idx, data) 

 

def tab_data(self, idx, key): 

"""Get tab data for a given key.""" 

400 ↛ 401line 400 didn't jump to line 401, because the condition on line 400 was never true if not 0 <= idx < self.count(): 

raise IndexError("Tab index ({}) out of range ({})!".format( 

idx, self.count())) 

data = self.tabData(idx) 

if data is None: 

data = {} 

return data[key] 

 

def tab_indicator_color(self, idx): 

"""Get the tab indicator color for the given index.""" 

try: 

return self.tab_data(idx, 'indicator-color') 

except KeyError: 

return QColor() 

 

def page_title(self, idx): 

"""Get the tab title user data. 

 

Args: 

idx: The tab index to get the title for. 

handle_unset: Whether to return an empty string on KeyError. 

""" 

try: 

return self.tab_data(idx, 'page-title') 

except KeyError: 

return '' 

 

def refresh(self): 

"""Properly repaint the tab bar and relayout tabs.""" 

# This is a horrible hack, but we need to do this so the underlying Qt 

# code sets layoutDirty so it actually relayouts the tabs. 

self.setIconSize(self.iconSize()) 

 

def _set_font(self): 

"""Set the tab bar font.""" 

self.setFont(config.val.fonts.tabs) 

self._set_icon_size() 

# clear tab size cache 

self._minimum_tab_size_hint_helper.cache_clear() 

 

def _set_icon_size(self): 

"""Set the tab bar favicon size.""" 

size = self.fontMetrics().height() - 2 

size *= config.val.tabs.favicons.scale 

self.setIconSize(QSize(size, size)) 

 

def _set_colors(self): 

"""Set the tab bar colors.""" 

p = self.palette() 

p.setColor(QPalette.Window, config.val.colors.tabs.bar.bg) 

self.setPalette(p) 

 

def mousePressEvent(self, e): 

"""Override mousePressEvent to close tabs if configured.""" 

button = config.val.tabs.close_mouse_button 

if (e.button() == Qt.RightButton and button == 'right' or 

e.button() == Qt.MiddleButton and button == 'middle'): 

e.accept() 

idx = self.tabAt(e.pos()) 

if idx == -1: 

action = config.val.tabs.close_mouse_button_on_bar 

if action == 'ignore': 

return 

elif action == 'new-tab': 

self.new_tab_requested.emit() 

return 

elif action == 'close-current': 

idx = self.currentIndex() 

elif action == 'close-last': 

idx = self.count() - 1 

self.tabCloseRequested.emit(idx) 

return 

super().mousePressEvent(e) 

 

def minimumTabSizeHint(self, index, ellipsis: bool = True) -> QSize: 

"""Set the minimum tab size to indicator/icon/... text. 

 

Args: 

index: The index of the tab to get a size hint for. 

ellipsis: Whether to use ellipsis to calculate width 

instead of the tab's text. 

Return: 

A QSize of the smallest tab size we can make. 

""" 

icon = self.tabIcon(index) 

icon_padding = self.style().pixelMetric(PixelMetrics.icon_padding, 

None, self) 

if icon.isNull(): 

icon_width = 0 

else: 

icon_width = min(icon.actualSize(self.iconSize()).width(), 

self.iconSize().width()) + icon_padding 

return self._minimum_tab_size_hint_helper(self.tabText(index), 

icon_width, 

ellipsis) 

 

@functools.lru_cache(maxsize=2**9) 

def _minimum_tab_size_hint_helper(self, tab_text: str, 

icon_width: int, 

ellipsis: bool) -> QSize: 

"""Helper function to cache tab results. 

 

Config values accessed in here should be added to _on_config_changed to 

ensure cache is flushed when needed. 

""" 

text = '\u2026' if ellipsis else tab_text 

# Don't ever shorten if text is shorter than the ellipsis 

 

def _text_to_width(text): 

# Calculate text width taking into account qt mnemonics 

return self.fontMetrics().size(Qt.TextShowMnemonic, text).width() 

text_width = min(_text_to_width(text), 

_text_to_width(tab_text)) 

padding = config.val.tabs.padding 

indicator_width = config.val.tabs.indicator.width 

indicator_padding = config.val.tabs.indicator.padding 

padding_h = padding.left + padding.right 

# Only add padding if indicator exists 

518 ↛ 520line 518 didn't jump to line 520, because the condition on line 518 was never false if indicator_width != 0: 

padding_h += indicator_padding.left + indicator_padding.right 

padding_v = padding.top + padding.bottom 

height = self.fontMetrics().height() + padding_v 

width = (text_width + icon_width + 

padding_h + indicator_width) 

return QSize(width, height) 

 

def _pinned_statistics(self) -> (int, int): 

"""Get the number of pinned tabs and the total width of pinned tabs.""" 

pinned_list = [idx for idx in range(self.count()) 

if self._tab_pinned(idx)] 

pinned_count = len(pinned_list) 

pinned_width = sum(self.minimumTabSizeHint(idx, ellipsis=False).width() 

for idx in pinned_list) 

return (pinned_count, pinned_width) 

 

def _tab_pinned(self, index: int) -> bool: 

"""Return True if tab is pinned.""" 

try: 

return self.tab_data(index, 'pinned') 

except KeyError: 

return False 

 

def tabSizeHint(self, index: int): 

"""Override tabSizeHint to customize qb's tab size. 

 

https://wiki.python.org/moin/PyQt/Customising%20tab%20bars 

 

Args: 

index: The index of the tab. 

 

Return: 

A QSize. 

""" 

minimum_size = self.minimumTabSizeHint(index) 

height = minimum_size.height() 

555 ↛ 556line 555 didn't jump to line 556, because the condition on line 555 was never true if self.vertical: 

confwidth = str(config.val.tabs.width) 

if confwidth.endswith('%'): 

main_window = objreg.get('main-window', scope='window', 

window=self._win_id) 

perc = int(confwidth.rstrip('%')) 

width = main_window.width() * perc / 100 

else: 

width = int(confwidth) 

size = QSize(max(minimum_size.width(), width), height) 

elif self.count() == 0: 

# This happens on startup on macOS. 

# We return it directly rather than setting `size' because we don't 

# want to ensure it's valid in this special case. 

return QSize() 

else: 

571 ↛ 575line 571 didn't jump to line 575, because the condition on line 571 was never false if config.val.tabs.pinned.shrink: 

pinned = self._tab_pinned(index) 

pinned_count, pinned_width = self._pinned_statistics() 

else: 

pinned = False 

pinned_count, pinned_width = 0, 0 

no_pinned_count = self.count() - pinned_count 

no_pinned_width = self.width() - pinned_width 

 

580 ↛ 583line 580 didn't jump to line 583, because the condition on line 580 was never true if pinned: 

# Give pinned tabs the minimum size they need to display their 

# titles, let Qt handle scaling it down if we get too small. 

width = self.minimumTabSizeHint(index, ellipsis=False).width() 

else: 

width = no_pinned_width / no_pinned_count 

 

# If no_pinned_width is not divisible by no_pinned_count, add a 

# pixel to some tabs so that there is no ugly leftover space. 

if (no_pinned_count > 0 and 

index < no_pinned_width % no_pinned_count): 

width += 1 

 

# If we don't have enough space, we return the minimum size so we 

# get scroll buttons as soon as needed. 

width = max(width, minimum_size.width()) 

 

size = QSize(width, height) 

qtutils.ensure_valid(size) 

return size 

 

def paintEvent(self, _e): 

"""Override paintEvent to draw the tabs like we want to.""" 

p = QStylePainter(self) 

selected = self.currentIndex() 

for idx in range(self.count()): 

tab = QStyleOptionTab() 

self.initStyleOption(tab, idx) 

 

# pylint: disable=bad-config-option 

setting = config.val.colors.tabs 

# pylint: enable=bad-config-option 

if idx == selected: 

setting = setting.selected 

setting = setting.odd if (idx + 1) % 2 else setting.even 

 

tab.palette.setColor(QPalette.Window, setting.bg) 

tab.palette.setColor(QPalette.WindowText, setting.fg) 

 

indicator_color = self.tab_indicator_color(idx) 

tab.palette.setColor(QPalette.Base, indicator_color) 

if tab.rect.right() < 0 or tab.rect.left() > self.width(): 

# Don't bother drawing a tab if the entire tab is outside of 

# the visible tab bar. 

continue 

p.drawControl(QStyle.CE_TabBarTab, tab) 

 

def tabInserted(self, idx): 

"""Update visibility when a tab was inserted.""" 

super().tabInserted(idx) 

self.maybe_hide() 

 

def tabRemoved(self, idx): 

"""Update visibility when a tab was removed.""" 

super().tabRemoved(idx) 

self.maybe_hide() 

 

def wheelEvent(self, e): 

"""Override wheelEvent to make the action configurable. 

 

Args: 

e: The QWheelEvent 

""" 

if config.val.tabs.mousewheel_switching: 

super().wheelEvent(e) 

else: 

tabbed_browser = objreg.get('tabbed-browser', scope='window', 

window=self._win_id) 

tabbed_browser.wheelEvent(e) 

 

 

@attr.s 

class Layouts: 

 

"""Layout information for tab. 

 

Used by TabBarStyle._tab_layout(). 

""" 

 

text = attr.ib() 

icon = attr.ib() 

indicator = attr.ib() 

 

 

class TabBarStyle(QCommonStyle): 

 

"""Qt style used by TabBar to fix some issues with the default one. 

 

This fixes the following things: 

- Remove the focus rectangle Ubuntu draws on tabs. 

- Force text to be left-aligned even though Qt has "centered" 

hardcoded. 

 

Unfortunately PyQt doesn't support QProxyStyle, so we need to do this the 

hard way... 

 

Based on: 

 

http://stackoverflow.com/a/17294081 

https://code.google.com/p/makehuman/source/browse/trunk/makehuman/lib/qtgui.py 

""" 

 

def __init__(self): 

"""Initialize all functions we're not overriding. 

 

This simply calls the corresponding function in self._style. 

""" 

self._style = QStyleFactory.create('Fusion') 

for method in ['drawComplexControl', 'drawItemPixmap', 

'generatedIconPixmap', 'hitTestComplexControl', 

'itemPixmapRect', 'itemTextRect', 'polish', 'styleHint', 

'subControlRect', 'unpolish', 'drawItemText', 

'sizeFromContents', 'drawPrimitive']: 

target = getattr(self._style, method) 

setattr(self, method, functools.partial(target)) 

super().__init__() 

 

def _draw_indicator(self, layouts, opt, p): 

"""Draw the tab indicator. 

 

Args: 

layouts: The layouts from _tab_layout. 

opt: QStyleOption from drawControl. 

p: QPainter from drawControl. 

""" 

color = opt.palette.base().color() 

rect = layouts.indicator 

707 ↛ 708line 707 didn't jump to line 708, because the condition on line 707 was never true if color.isValid() and rect.isValid(): 

p.fillRect(rect, color) 

 

def _draw_icon(self, layouts, opt, p): 

"""Draw the tab icon. 

 

Args: 

layouts: The layouts from _tab_layout. 

opt: QStyleOption 

p: QPainter 

""" 

qtutils.ensure_valid(layouts.icon) 

icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled 

else QIcon.Disabled) 

icon_state = (QIcon.On if opt.state & QStyle.State_Selected 

else QIcon.Off) 

icon = opt.icon.pixmap(opt.iconSize, icon_mode, icon_state) 

self._style.drawItemPixmap(p, layouts.icon, Qt.AlignCenter, icon) 

 

def drawControl(self, element, opt, p, widget=None): 

"""Override drawControl to draw odd tabs in a different color. 

 

Draws the given element with the provided painter with the style 

options specified by option. 

 

Args: 

element: ControlElement 

opt: QStyleOption 

p: QPainter 

widget: QWidget 

""" 

738 ↛ 741line 738 didn't jump to line 741, because the condition on line 738 was never true if element not in [QStyle.CE_TabBarTab, QStyle.CE_TabBarTabShape, 

QStyle.CE_TabBarTabLabel]: 

# Let the real style draw it. 

self._style.drawControl(element, opt, p, widget) 

return 

 

layouts = self._tab_layout(opt) 

745 ↛ 746line 745 didn't jump to line 746, because the condition on line 745 was never true if layouts is None: 

log.misc.warning("Could not get layouts for tab!") 

return 

 

if element == QStyle.CE_TabBarTab: 

# We override this so we can control TabBarTabShape/TabBarTabLabel. 

self.drawControl(QStyle.CE_TabBarTabShape, opt, p, widget) 

self.drawControl(QStyle.CE_TabBarTabLabel, opt, p, widget) 

elif element == QStyle.CE_TabBarTabShape: 

p.fillRect(opt.rect, opt.palette.window()) 

self._draw_indicator(layouts, opt, p) 

# We use super() rather than self._style here because we don't want 

# any sophisticated drawing. 

super().drawControl(QStyle.CE_TabBarTabShape, opt, p, widget) 

759 ↛ 768line 759 didn't jump to line 768, because the condition on line 759 was never false elif element == QStyle.CE_TabBarTabLabel: 

760 ↛ 761line 760 didn't jump to line 761, because the condition on line 760 was never true if not opt.icon.isNull() and layouts.icon.isValid(): 

self._draw_icon(layouts, opt, p) 

alignment = (config.val.tabs.title.alignment | 

Qt.AlignVCenter | Qt.TextHideMnemonic) 

self._style.drawItemText(p, layouts.text, alignment, opt.palette, 

opt.state & QStyle.State_Enabled, 

opt.text, QPalette.WindowText) 

else: 

raise ValueError("Invalid element {!r}".format(element)) 

 

def pixelMetric(self, metric, option=None, widget=None): 

"""Override pixelMetric to not shift the selected tab. 

 

Args: 

metric: PixelMetric 

option: const QStyleOption * 

widget: const QWidget * 

 

Return: 

An int. 

""" 

if metric in [QStyle.PM_TabBarTabShiftHorizontal, 

QStyle.PM_TabBarTabShiftVertical, 

QStyle.PM_TabBarTabHSpace, 

QStyle.PM_TabBarTabVSpace, 

QStyle.PM_TabBarScrollButtonWidth]: 

return 0 

elif metric == PixelMetrics.icon_padding: 

return 4 

else: 

return self._style.pixelMetric(metric, option, widget) 

 

def subElementRect(self, sr, opt, widget=None): 

"""Override subElementRect to use our own _tab_layout implementation. 

 

Args: 

sr: SubElement 

opt: QStyleOption 

widget: QWidget 

 

Return: 

A QRect. 

""" 

if sr == QStyle.SE_TabBarTabText: 

layouts = self._tab_layout(opt) 

805 ↛ 806line 805 didn't jump to line 806, because the condition on line 805 was never true if layouts is None: 

log.misc.warning("Could not get layouts for tab!") 

return QRect() 

return layouts.text 

elif sr in [QStyle.SE_TabWidgetTabBar, 

QStyle.SE_TabBarScrollLeftButton]: 

# Handling SE_TabBarScrollLeftButton so the left scroll button is 

# aligned properly. Otherwise, empty space will be shown after the 

# last tab even though the button width is set to 0 

# 

# Need to use super() because we also use super() to render 

# element in drawControl(); otherwise, we may get bit by 

# style differences... 

return super().subElementRect(sr, opt, widget) 

else: 

return self._style.subElementRect(sr, opt, widget) 

 

def _tab_layout(self, opt): 

"""Compute the text/icon rect from the opt rect. 

 

This is based on Qt's QCommonStylePrivate::tabLayout 

(qtbase/src/widgets/styles/qcommonstyle.cpp) as we can't use the 

private implementation. 

 

Args: 

opt: QStyleOptionTab 

 

Return: 

A Layout object with two QRects. 

""" 

padding = config.val.tabs.padding 

indicator_padding = config.val.tabs.indicator.padding 

 

text_rect = QRect(opt.rect) 

839 ↛ 842line 839 didn't jump to line 842, because the condition on line 839 was never true if not text_rect.isValid(): 

# This happens sometimes according to crash reports, but no idea 

# why... 

return None 

 

text_rect.adjust(padding.left, padding.top, -padding.right, 

-padding.bottom) 

 

indicator_width = config.val.tabs.indicator.width 

848 ↛ 849line 848 didn't jump to line 849, because the condition on line 848 was never true if indicator_width == 0: 

indicator_rect = QRect() 

else: 

indicator_rect = QRect(opt.rect) 

qtutils.ensure_valid(indicator_rect) 

indicator_rect.adjust(padding.left + indicator_padding.left, 

padding.top + indicator_padding.top, 

0, 

-(padding.bottom + indicator_padding.bottom)) 

indicator_rect.setWidth(indicator_width) 

 

text_rect.adjust(indicator_width + indicator_padding.left + 

indicator_padding.right, 0, 0, 0) 

 

icon_rect = self._get_icon_rect(opt, text_rect) 

863 ↛ 864line 863 didn't jump to line 864, because the condition on line 863 was never true if icon_rect.isValid(): 

icon_padding = self.pixelMetric(PixelMetrics.icon_padding, opt) 

text_rect.adjust(icon_rect.width() + icon_padding, 0, 0, 0) 

 

text_rect = self._style.visualRect(opt.direction, opt.rect, text_rect) 

return Layouts(text=text_rect, icon=icon_rect, 

indicator=indicator_rect) 

 

def _get_icon_rect(self, opt, text_rect): 

"""Get a QRect for the icon to draw. 

 

Args: 

opt: QStyleOptionTab 

text_rect: The QRect for the text. 

 

Return: 

A QRect. 

""" 

icon_size = opt.iconSize 

882 ↛ 883line 882 didn't jump to line 883, because the condition on line 882 was never true if not icon_size.isValid(): 

icon_extent = self.pixelMetric(QStyle.PM_SmallIconSize) 

icon_size = QSize(icon_extent, icon_extent) 

icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled 

else QIcon.Disabled) 

icon_state = (QIcon.On if opt.state & QStyle.State_Selected 

else QIcon.Off) 

# reserve space for favicon when tab bar is vertical (issue #1968) 

position = config.val.tabs.position 

891 ↛ 893line 891 didn't jump to line 893, because the condition on line 891 was never true if (position in [QTabWidget.East, QTabWidget.West] and 

config.val.tabs.favicons.show): 

tab_icon_size = icon_size 

else: 

actual_size = opt.icon.actualSize(icon_size, icon_mode, icon_state) 

tab_icon_size = QSize( 

min(actual_size.width(), icon_size.width()), 

min(actual_size.height(), icon_size.height())) 

 

icon_top = text_rect.center().y() + 1 - tab_icon_size.height() / 2 

icon_rect = QRect(QPoint(text_rect.left(), icon_top), tab_icon_size) 

icon_rect = self._style.visualRect(opt.direction, opt.rect, icon_rect) 

return icon_rect