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

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

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

 

"""Types for options in qutebrowser's configuration. 

 

Those types are used in configdata.yml as type of a setting. 

 

Most of them are pretty generic, but some of them are e.g. specific String 

subclasses with valid_values set, as that particular "type" is used multiple 

times in the config. 

 

A setting value can be represented in three different ways: 

 

1) As an object which can be represented in YAML: 

str, list, dict, int, float, True/False/None 

This is what qutebrowser actually saves internally, and also what it gets 

from the YAML or config.py. 

2) As a string. This is e.g. used by the :set command. 

3) As the value the code which uses it expects, e.g. enum members. 

 

Config types can do different conversations: 

 

- Object to string with .to_str() (1 -> 2) 

- String to object with .from_str() (2 -> 1) 

- Object to code with .to_py() (1 -> 3) 

This also validates whether the object is actually correct (type/value). 

""" 

 

import re 

import html 

import codecs 

import os.path 

import itertools 

import warnings 

import datetime 

import functools 

import operator 

import json 

 

import attr 

import yaml 

from PyQt5.QtCore import QUrl, Qt 

from PyQt5.QtGui import QColor, QFont 

from PyQt5.QtWidgets import QTabWidget, QTabBar 

 

from qutebrowser.commands import cmdutils 

from qutebrowser.config import configexc 

from qutebrowser.utils import standarddir, utils, qtutils, urlutils 

 

 

SYSTEM_PROXY = object() # Return value for Proxy type 

 

# Taken from configparser 

BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True, 

'0': False, 'no': False, 'false': False, 'off': False} 

 

 

class ValidValues: 

 

"""Container for valid values for a given type. 

 

Attributes: 

values: A list with the allowed untransformed values. 

descriptions: A dict with value/desc mappings. 

generate_docs: Whether to show the values in the docs. 

""" 

 

def __init__(self, *values, generate_docs=True): 

if not values: 

raise ValueError("ValidValues with no values makes no sense!") 

self.descriptions = {} 

self.values = [] 

self.generate_docs = generate_docs 

for value in values: 

if isinstance(value, str): 

# Value without description 

self.values.append(value) 

elif isinstance(value, dict): 

# List of dicts from configdata.yml 

assert len(value) == 1, value 

value, desc = list(value.items())[0] 

self.values.append(value) 

self.descriptions[value] = desc 

else: 

# (value, description) tuple 

self.values.append(value[0]) 

self.descriptions[value[0]] = value[1] 

 

def __contains__(self, val): 

return val in self.values 

 

def __iter__(self): 

return self.values.__iter__() 

 

def __repr__(self): 

return utils.get_repr(self, values=self.values, 

descriptions=self.descriptions) 

 

def __eq__(self, other): 

return (self.values == other.values and 

self.descriptions == other.descriptions) 

 

 

class BaseType: 

 

"""A type used for a setting value. 

 

Attributes: 

none_ok: Whether to convert to None for an empty string. 

 

Class attributes: 

valid_values: Possible values if they can be expressed as a fixed 

string. ValidValues instance. 

""" 

 

def __init__(self, none_ok=False): 

self.none_ok = none_ok 

self.valid_values = None 

 

def get_name(self): 

"""Get a name for the type for documentation.""" 

return self.__class__.__name__ 

 

def get_valid_values(self): 

"""Get the type's valid values for documentation.""" 

return self.valid_values 

 

def _basic_py_validation(self, value, pytype): 

"""Do some basic validation for Python values (emptyness, type). 

 

Arguments: 

value: The value to check. 

pytype: A Python type to check the value against. 

""" 

if (value is None or (pytype == list and value == []) or 

(pytype == dict and value == {})): 

if not self.none_ok: 

raise configexc.ValidationError(value, "may not be null!") 

else: 

return 

 

if (not isinstance(value, pytype) or 

pytype is int and isinstance(value, bool)): 

if isinstance(pytype, tuple): 

expected = ' or '.join(typ.__name__ for typ in pytype) 

else: 

expected = pytype.__name__ 

raise configexc.ValidationError( 

value, "expected a value of type {} but got {}.".format( 

expected, type(value).__name__)) 

 

if isinstance(value, str): 

self._basic_str_validation(value) 

 

def _basic_str_validation(self, value): 

"""Do some basic validation for string values. 

 

This checks that the value isn't empty and doesn't contain any 

unprintable chars. 

 

Arguments: 

value: The value to check. 

""" 

assert isinstance(value, str), value 

if not value and not self.none_ok: 

raise configexc.ValidationError(value, "may not be empty!") 

if any(ord(c) < 32 or ord(c) == 0x7f for c in value): 

raise configexc.ValidationError( 

value, "may not contain unprintable chars!") 

 

def _validate_surrogate_escapes(self, full_value, value): 

"""Make sure the given value doesn't contain surrogate escapes. 

 

This is used for values passed to json.dump, as it can't handle those. 

""" 

if not isinstance(value, str): 

return 

if any(ord(c) > 0xFFFF for c in value): 

raise configexc.ValidationError( 

full_value, "may not contain surrogate escapes!") 

 

def _validate_valid_values(self, value): 

"""Validate value against possible values. 

 

The default implementation checks the value against self.valid_values 

if it was defined. 

 

Args: 

value: The value to validate. 

""" 

if self.valid_values is not None: 

if value not in self.valid_values: 

raise configexc.ValidationError( 

value, 

"valid values: {}".format(', '.join(self.valid_values))) 

 

def from_str(self, value): 

"""Get the setting value from a string. 

 

By default this invokes to_py() for validation and returns the 

unaltered value. This means that if to_py() returns a string rather 

than something more sophisticated, this doesn't need to be implemented. 

 

Args: 

value: The original string value. 

 

Return: 

The transformed value. 

""" 

self._basic_str_validation(value) 

self.to_py(value) # for validation 

if not value: 

return None 

return value 

 

def from_obj(self, value): 

"""Get the setting value from a config.py/YAML object.""" 

return value 

 

def to_py(self, value): 

"""Get the setting value from a Python value. 

 

Args: 

value: The value we got from Python/YAML. 

 

Return: 

The transformed value. 

 

Raise: 

configexc.ValidationError if the value was invalid. 

""" 

raise NotImplementedError 

 

def to_str(self, value): 

"""Get a string from the setting value. 

 

The resulting string should be parseable again by from_str. 

""" 

if value is None: 

return '' 

assert isinstance(value, str), value 

return value 

 

def to_doc(self, value, indent=0): 

"""Get a string with the given value for the documentation. 

 

This currently uses asciidoc syntax. 

""" 

utils.unused(indent) # only needed for Dict/List 

str_value = self.to_str(value) 

if not str_value: 

return 'empty' 

return '+pass:[{}]+'.format(html.escape(str_value)) 

 

def complete(self): 

"""Return a list of possible values for completion. 

 

The default implementation just returns valid_values, but it might be 

useful to override this for special cases. 

 

Return: 

A list of (value, description) tuples or None. 

""" 

if self.valid_values is None: 

return None 

else: 

out = [] 

for val in self.valid_values: 

try: 

desc = self.valid_values.descriptions[val] 

except KeyError: 

# Some values are self-explaining and don't need a 

# description. 

desc = "" 

out.append((val, desc)) 

return out 

 

 

class MappingType(BaseType): 

 

"""Base class for any setting which has a mapping to the given values. 

 

Attributes: 

MAPPING: The mapping to use. 

""" 

 

MAPPING = {} 

 

def __init__(self, none_ok=False, valid_values=None): 

super().__init__(none_ok) 

self.valid_values = valid_values 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

self._validate_valid_values(value.lower()) 

return self.MAPPING[value.lower()] 

 

 

class String(BaseType): 

 

"""A string value. 

 

See the setting's valid values for more information on allowed values. 

 

Attributes: 

minlen: Minimum length (inclusive). 

maxlen: Maximum length (inclusive). 

forbidden: Forbidden chars in the string. 

completions: completions to be used, or None 

""" 

 

def __init__(self, *, minlen=None, maxlen=None, forbidden=None, 

encoding=None, none_ok=False, completions=None, 

valid_values=None): 

super().__init__(none_ok) 

self.valid_values = valid_values 

 

if minlen is not None and minlen < 1: 

raise ValueError("minlen ({}) needs to be >= 1!".format(minlen)) 

elif maxlen is not None and maxlen < 1: 

raise ValueError("maxlen ({}) needs to be >= 1!".format(maxlen)) 

elif maxlen is not None and minlen is not None and maxlen < minlen: 

raise ValueError("minlen ({}) needs to be <= maxlen ({})!".format( 

minlen, maxlen)) 

self.minlen = minlen 

self.maxlen = maxlen 

self.forbidden = forbidden 

self._completions = completions 

self.encoding = encoding 

 

def _validate_encoding(self, value): 

"""Check if the given value fits into the configured encoding. 

 

Raises ValidationError if not. 

 

Args: 

value: The value to check. 

""" 

if self.encoding is None: 

return 

 

try: 

value.encode(self.encoding) 

except UnicodeEncodeError as e: 

msg = "{!r} contains non-{} characters: {}".format( 

value, self.encoding, e) 

raise configexc.ValidationError(value, msg) 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

self._validate_encoding(value) 

self._validate_valid_values(value) 

 

if self.forbidden is not None and any(c in value 

for c in self.forbidden): 

raise configexc.ValidationError(value, "may not contain the chars " 

"'{}'".format(self.forbidden)) 

if self.minlen is not None and len(value) < self.minlen: 

raise configexc.ValidationError(value, "must be at least {} chars " 

"long!".format(self.minlen)) 

if self.maxlen is not None and len(value) > self.maxlen: 

raise configexc.ValidationError(value, "must be at most {} chars " 

"long!".format(self.maxlen)) 

 

return value 

 

def complete(self): 

if self._completions is not None: 

return self._completions 

else: 

return super().complete() 

 

 

class UniqueCharString(String): 

 

"""A string which may not contain duplicate chars.""" 

 

def to_py(self, value): 

value = super().to_py(value) 

if not value: 

return None 

 

# Check for duplicate values 

if len(set(value)) != len(value): 

raise configexc.ValidationError( 

value, "String contains duplicate values!") 

 

return value 

 

 

class List(BaseType): 

 

"""A list of values. 

 

When setting from a string, pass a json-like list, e.g. `["one", "two"]`. 

""" 

 

_show_valtype = True 

 

def __init__(self, valtype, none_ok=False, length=None): 

super().__init__(none_ok) 

self.valtype = valtype 

self.length = length 

 

def get_name(self): 

name = super().get_name() 

if self._show_valtype: 

name += " of " + self.valtype.get_name() 

return name 

 

def get_valid_values(self): 

return self.valtype.get_valid_values() 

 

def from_str(self, value): 

self._basic_str_validation(value) 

if not value: 

return None 

 

try: 

yaml_val = utils.yaml_load(value) 

except yaml.YAMLError as e: 

raise configexc.ValidationError(value, str(e)) 

 

# For the values, we actually want to call to_py, as we did parse them 

# from YAML, so they are numbers/booleans/... already. 

self.to_py(yaml_val) 

return yaml_val 

 

def from_obj(self, value): 

if value is None: 

return [] 

return value 

 

def to_py(self, value): 

self._basic_py_validation(value, list) 

if not value: 

return [] 

 

for val in value: 

self._validate_surrogate_escapes(value, val) 

 

if self.length is not None and len(value) != self.length: 

raise configexc.ValidationError(value, "Exactly {} values need to " 

"be set!".format(self.length)) 

return [self.valtype.to_py(v) for v in value] 

 

def to_str(self, value): 

if not value: 

# An empty list is treated just like None -> empty string 

return '' 

return json.dumps(value) 

 

def to_doc(self, value, indent=0): 

if not value: 

return 'empty' 

 

# Might work, but untested 

assert not isinstance(self.valtype, (Dict, List)), self.valtype 

 

lines = ['\n'] 

prefix = '-' if not indent else '*' * indent 

for elem in value: 

lines.append('{} {}'.format( 

prefix, 

self.valtype.to_doc(elem, indent=indent+1))) 

return '\n'.join(lines) 

 

 

class ListOrValue(BaseType): 

 

"""A list of values, or a single value. 

 

// 

 

Internally, the value is stored as either a value (of valtype), or a list. 

to_py() then ensures that it's always a list. 

""" 

 

_show_valtype = True 

 

def __init__(self, valtype, *args, none_ok=False, **kwargs): 

super().__init__(none_ok) 

assert not isinstance(valtype, (List, ListOrValue)), valtype 

self.listtype = List(valtype, none_ok=none_ok, *args, **kwargs) 

self.valtype = valtype 

 

def get_name(self): 

return self.listtype.get_name() + ', or ' + self.valtype.get_name() 

 

def get_valid_values(self): 

return self.valtype.get_valid_values() 

 

def from_str(self, value): 

try: 

return self.listtype.from_str(value) 

except configexc.ValidationError: 

return self.valtype.from_str(value) 

 

def from_obj(self, value): 

if value is None: 

return [] 

return value 

 

def to_py(self, value): 

try: 

return [self.valtype.to_py(value)] 

except configexc.ValidationError: 

return self.listtype.to_py(value) 

 

def to_str(self, value): 

if value is None: 

return '' 

 

if isinstance(value, list): 

if len(value) == 1: 

return self.valtype.to_str(value[0]) 

else: 

return self.listtype.to_str(value) 

else: 

return self.valtype.to_str(value) 

 

def to_doc(self, value, indent=0): 

if value is None: 

return 'empty' 

 

if isinstance(value, list): 

if len(value) == 1: 

return self.valtype.to_doc(value[0], indent) 

else: 

return self.listtype.to_doc(value, indent) 

else: 

return self.valtype.to_doc(value, indent) 

 

 

class FlagList(List): 

 

"""A list of flags. 

 

Lists with duplicate flags are invalid. Each item is checked against 

the valid values of the setting. 

""" 

 

combinable_values = None 

 

_show_valtype = False 

 

def __init__(self, none_ok=False, valid_values=None, length=None): 

super().__init__(valtype=String(), none_ok=none_ok, length=length) 

self.valtype.valid_values = valid_values 

 

def _check_duplicates(self, values): 

if len(set(values)) != len(values): 

raise configexc.ValidationError( 

values, "List contains duplicate values!") 

 

def to_py(self, value): 

vals = super().to_py(value) 

self._check_duplicates(vals) 

return vals 

 

def complete(self): 

valid_values = self.valtype.valid_values 

if valid_values is None: 

return None 

 

out = [] 

# Single value completions 

for value in valid_values: 

desc = valid_values.descriptions.get(value, "") 

out.append((json.dumps([value]), desc)) 

 

combinables = self.combinable_values 

if combinables is None: 

combinables = list(valid_values) 

# Generate combinations of each possible value combination 

for size in range(2, len(combinables) + 1): 

for combination in itertools.combinations(combinables, size): 

out.append((json.dumps(combination), '')) 

return out 

 

 

class Bool(BaseType): 

 

"""A boolean setting, either `true` or `false`. 

 

When setting from a string, `1`, `yes`, `on` and `true` count as true, 

while `0`, `no`, `off` and `false` count as false (case-insensitive). 

""" 

 

def __init__(self, none_ok=False): 

super().__init__(none_ok) 

self.valid_values = ValidValues('true', 'false', generate_docs=False) 

 

def to_py(self, value): 

self._basic_py_validation(value, bool) 

return value 

 

def from_str(self, value): 

self._basic_str_validation(value) 

if not value: 

return None 

 

try: 

return BOOLEAN_STATES[value.lower()] 

except KeyError: 

raise configexc.ValidationError(value, "must be a boolean!") 

 

def to_str(self, value): 

mapping = { 

None: '', 

True: 'true', 

False: 'false', 

} 

return mapping[value] 

 

 

class BoolAsk(Bool): 

 

"""Like `Bool`, but `ask` is allowed as additional value.""" 

 

def __init__(self, none_ok=False): 

super().__init__(none_ok) 

self.valid_values = ValidValues('true', 'false', 'ask') 

 

def to_py(self, value): 

# basic validation unneeded if it's == 'ask' and done by Bool if we 

# call super().to_py 

if isinstance(value, str) and value.lower() == 'ask': 

return 'ask' 

return super().to_py(value) 

 

def from_str(self, value): 

# basic validation unneeded if it's == 'ask' and done by Bool if we 

# call super().from_str 

if isinstance(value, str) and value.lower() == 'ask': 

return 'ask' 

return super().from_str(value) 

 

def to_str(self, value): 

mapping = { 

None: '', 

True: 'true', 

False: 'false', 

'ask': 'ask', 

} 

return mapping[value] 

 

 

class _Numeric(BaseType): # pylint: disable=abstract-method 

 

"""Base class for Float/Int. 

 

Attributes: 

minval: Minimum value (inclusive). 

maxval: Maximum value (inclusive). 

""" 

 

def __init__(self, minval=None, maxval=None, none_ok=False): 

super().__init__(none_ok) 

self.minval = self._parse_bound(minval) 

self.maxval = self._parse_bound(maxval) 

if self.maxval is not None and self.minval is not None: 

if self.maxval < self.minval: 

raise ValueError("minval ({}) needs to be <= maxval ({})!" 

.format(self.minval, self.maxval)) 

 

def _parse_bound(self, bound): 

"""Get a numeric bound from a string like 'maxint'.""" 

if bound == 'maxint': 

return qtutils.MAXVALS['int'] 

elif bound == 'maxint64': 

return qtutils.MAXVALS['int64'] 

else: 

if bound is not None: 

assert isinstance(bound, (int, float)), bound 

return bound 

 

def _validate_bounds(self, value, suffix=''): 

"""Validate self.minval and self.maxval.""" 

if value is None: 

return 

elif self.minval is not None and value < self.minval: 

raise configexc.ValidationError( 

value, "must be {}{} or bigger!".format(self.minval, suffix)) 

elif self.maxval is not None and value > self.maxval: 

raise configexc.ValidationError( 

value, "must be {}{} or smaller!".format(self.maxval, suffix)) 

 

def to_str(self, value): 

if value is None: 

return '' 

return str(value) 

 

 

class Int(_Numeric): 

 

"""Base class for an integer setting.""" 

 

def from_str(self, value): 

self._basic_str_validation(value) 

if not value: 

return None 

 

try: 

intval = int(value) 

except ValueError: 

raise configexc.ValidationError(value, "must be an integer!") 

self.to_py(intval) 

return intval 

 

def to_py(self, value): 

self._basic_py_validation(value, int) 

self._validate_bounds(value) 

return value 

 

 

class Float(_Numeric): 

 

"""Base class for a float setting.""" 

 

def from_str(self, value): 

self._basic_str_validation(value) 

if not value: 

return None 

 

try: 

floatval = float(value) 

except ValueError: 

raise configexc.ValidationError(value, "must be a float!") 

self.to_py(floatval) 

return floatval 

 

def to_py(self, value): 

self._basic_py_validation(value, (int, float)) 

self._validate_bounds(value) 

return value 

 

 

class Perc(_Numeric): 

 

"""A percentage.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, (float, int, str)) 

if not value: 

return None 

 

if isinstance(value, str): 

value = value.rstrip('%') 

try: 

value = float(value) 

except ValueError: 

raise configexc.ValidationError( 

value, "must be a valid number!") 

self._validate_bounds(value, suffix='%') 

return value 

 

def to_str(self, value): 

if value is None: 

return '' 

return value 

 

 

class PercOrInt(_Numeric): 

 

"""Percentage or integer. 

 

Attributes: 

minperc: Minimum value for percentage (inclusive). 

maxperc: Maximum value for percentage (inclusive). 

minint: Minimum value for integer (inclusive). 

maxint: Maximum value for integer (inclusive). 

""" 

 

def __init__(self, minperc=None, maxperc=None, minint=None, maxint=None, 

none_ok=False): 

super().__init__(minval=minint, maxval=maxint, none_ok=none_ok) 

self.minperc = self._parse_bound(minperc) 

self.maxperc = self._parse_bound(maxperc) 

if (self.maxperc is not None and self.minperc is not None and 

self.maxperc < self.minperc): 

raise ValueError("minperc ({}) needs to be <= maxperc " 

"({})!".format(self.minperc, self.maxperc)) 

 

def from_str(self, value): 

self._basic_str_validation(value) 

if not value: 

return None 

 

if value.endswith('%'): 

self.to_py(value) 

return value 

 

try: 

intval = int(value) 

except ValueError: 

raise configexc.ValidationError(value, 

"must be integer or percentage!") 

self.to_py(intval) 

return intval 

 

def to_py(self, value): 

"""Expect a value like '42%' as string, or 23 as int.""" 

self._basic_py_validation(value, (int, str)) 

if value is None: 

return None 

 

if isinstance(value, str): 

if not value.endswith('%'): 

raise configexc.ValidationError( 

value, "needs to end with % or be an integer") 

 

try: 

intval = int(value[:-1]) 

except ValueError: 

raise configexc.ValidationError(value, "invalid percentage!") 

 

if self.minperc is not None and intval < self.minperc: 

raise configexc.ValidationError(value, "must be {}% or " 

"more!".format(self.minperc)) 

if self.maxperc is not None and intval > self.maxperc: 

raise configexc.ValidationError(value, "must be {}% or " 

"less!".format(self.maxperc)) 

 

# Note we don't actually return the integer here, as we need to 

# know whether it was a percentage. 

else: 

self._validate_bounds(value) 

return value 

 

 

class Command(BaseType): 

 

"""A qutebrowser command with arguments. 

 

// 

 

Since validation is quite tricky here, we don't do so, and instead let 

invalid commands (in bindings/aliases) fail when used. 

""" 

 

def complete(self): 

out = [] 

for cmdname, obj in cmdutils.cmd_dict.items(): 

out.append((cmdname, obj.desc)) 

return out 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

return value 

 

 

class ColorSystem(MappingType): 

 

"""The color system to use for color interpolation.""" 

 

def __init__(self, none_ok=False): 

super().__init__( 

none_ok, 

valid_values=ValidValues( 

('rgb', "Interpolate in the RGB color system."), 

('hsv', "Interpolate in the HSV color system."), 

('hsl', "Interpolate in the HSL color system."), 

('none', "Don't show a gradient."))) 

 

MAPPING = { 

'rgb': QColor.Rgb, 

'hsv': QColor.Hsv, 

'hsl': QColor.Hsl, 

'none': None, 

} 

 

 

class QtColor(BaseType): 

 

"""A color value. 

 

A value can be in one of the following formats: 

 

* `#RGB`/`#RRGGBB`/`#RRRGGGBBB`/`#RRRRGGGGBBBB` 

* An SVG color name as specified in 

http://www.w3.org/TR/SVG/types.html#ColorKeywords[the W3C specification]. 

* transparent (no color) 

""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

color = QColor(value) 

if color.isValid(): 

return color 

else: 

raise configexc.ValidationError(value, "must be a valid color") 

 

 

class QssColor(BaseType): 

 

"""A color value supporting gradients. 

 

A value can be in one of the following formats: 

 

* `#RGB`/`#RRGGBB`/`#RRRGGGBBB`/`#RRRRGGGGBBBB` 

* An SVG color name as specified in 

http://www.w3.org/TR/SVG/types.html#ColorKeywords[the W3C specification]. 

* transparent (no color) 

* `rgb(r, g, b)` / `rgba(r, g, b, a)` (values 0-255 or percentages) 

* `hsv(h, s, v)` / `hsva(h, s, v, a)` (values 0-255, hue 0-359) 

* A gradient as explained in 

http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-property-types[the Qt documentation] 

under ``Gradient'' 

""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

functions = ['rgb', 'rgba', 'hsv', 'hsva', 'qlineargradient', 

'qradialgradient', 'qconicalgradient'] 

if (any(value.startswith(func + '(') for func in functions) and 

value.endswith(')')): 

# QColor doesn't handle these 

return value 

 

if not QColor.isValidColor(value): 

raise configexc.ValidationError(value, "must be a valid color") 

 

return value 

 

 

class Font(BaseType): 

 

"""A font family, with optional style/weight/size. 

 

* Style: `normal`/`italic`/`oblique` 

* Weight: `normal`, `bold`, `100`..`900` 

* Size: _number_ `px`/`pt` 

""" 

 

# Gets set when the config is initialized. 

monospace_fonts = None 

font_regex = re.compile(r""" 

( 

( 

# style 

(?P<style>normal|italic|oblique) | 

# weight (named | 100..900) 

( 

(?P<weight>[123456789]00) | 

(?P<namedweight>normal|bold) 

) | 

# size (<float>pt | <int>px) 

(?P<size>[0-9]+((\.[0-9]+)?[pP][tT]|[pP][xX])) 

)\ # size/weight/style are space-separated 

)* # 0-inf size/weight/style tags 

(?P<family>.+) # mandatory font family""", re.VERBOSE) 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

if not self.font_regex.fullmatch(value): # pragma: no cover 

# This should never happen, as the regex always matches everything 

# as family. 

raise configexc.ValidationError(value, "must be a valid font") 

 

if value.endswith(' monospace') and self.monospace_fonts is not None: 

return value.replace('monospace', self.monospace_fonts) 

return value 

 

 

class FontFamily(Font): 

 

"""A Qt font family.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

match = self.font_regex.fullmatch(value) 

if not match: # pragma: no cover 

# This should never happen, as the regex always matches everything 

# as family. 

raise configexc.ValidationError(value, "must be a valid font") 

for group in 'style', 'weight', 'namedweight', 'size': 

if match.group(group): 

raise configexc.ValidationError(value, "may not include a " 

"{}!".format(group)) 

 

return value 

 

 

class QtFont(Font): 

 

"""A Font which gets converted to a QFont.""" 

 

__doc__ = Font.__doc__ # for src2asciidoc.py 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

style_map = { 

'normal': QFont.StyleNormal, 

'italic': QFont.StyleItalic, 

'oblique': QFont.StyleOblique, 

} 

weight_map = { 

'normal': QFont.Normal, 

'bold': QFont.Bold, 

} 

font = QFont() 

font.setStyle(QFont.StyleNormal) 

font.setWeight(QFont.Normal) 

 

match = self.font_regex.fullmatch(value) 

if not match: # pragma: no cover 

# This should never happen, as the regex always matches everything 

# as family. 

raise configexc.ValidationError(value, "must be a valid font") 

 

style = match.group('style') 

weight = match.group('weight') 

namedweight = match.group('namedweight') 

size = match.group('size') 

family = match.group('family') 

if style: 

font.setStyle(style_map[style]) 

if namedweight: 

font.setWeight(weight_map[namedweight]) 

if weight: 

# based on qcssparser.cpp:setFontWeightFromValue 

font.setWeight(min(int(weight) / 8, 99)) 

if size: 

if size.lower().endswith('pt'): 

font.setPointSizeF(float(size[:-2])) 

elif size.lower().endswith('px'): 

font.setPixelSize(int(size[:-2])) 

else: 

# This should never happen as the regex only lets pt/px 

# through. 

raise ValueError("Unexpected size unit in {!r}!".format( 

size)) # pragma: no cover 

 

if family == 'monospace' and self.monospace_fonts is not None: 

family = self.monospace_fonts 

# The Qt CSS parser handles " and ' before passing the string to 

# QFont.setFamily. We could do proper CSS-like parsing here, but since 

# hopefully nobody will ever have a font with quotes in the family (if 

# that's even possible), we take a much more naive approach. 

family = family.replace('"', '').replace("'", '') 

font.setFamily(family) 

 

return font 

 

 

class Regex(BaseType): 

 

"""A regular expression. 

 

When setting from `config.py`, both a string or a `re.compile(...)` object 

are valid. 

 

Attributes: 

flags: The flags to be used when a string is passed. 

_regex_type: The Python type of a regex object. 

""" 

 

def __init__(self, flags=0, none_ok=False): 

super().__init__(none_ok) 

self._regex_type = type(re.compile('')) 

# Parse flags from configdata.yml 

if flags == 0: 

self.flags = flags 

else: 

self.flags = functools.reduce( 

operator.or_, 

(getattr(re, flag.strip()) for flag in flags.split(' | '))) 

 

def _compile_regex(self, pattern): 

"""Check if the given regex is valid. 

 

This is more complicated than it could be since there's a warning on 

invalid escapes with newer Python versions, and we want to catch that 

case and treat it as invalid. 

""" 

with warnings.catch_warnings(record=True) as recorded_warnings: 

warnings.simplefilter('always') 

try: 

compiled = re.compile(pattern, self.flags) 

except re.error as e: 

raise configexc.ValidationError( 

pattern, "must be a valid regex - " + str(e)) 

except RuntimeError: # pragma: no cover 

raise configexc.ValidationError( 

pattern, "must be a valid regex - recursion depth " 

"exceeded") 

 

for w in recorded_warnings: 

if (issubclass(w.category, DeprecationWarning) and 

str(w.message).startswith('bad escape')): 

raise configexc.ValidationError( 

pattern, "must be a valid regex - " + str(w.message)) 

else: 

warnings.warn(w.message) 

 

return compiled 

 

def to_py(self, value): 

"""Get a compiled regex from either a string or a regex object.""" 

self._basic_py_validation(value, (str, self._regex_type)) 

if not value: 

return None 

elif isinstance(value, str): 

return self._compile_regex(value) 

else: 

return value 

 

def to_str(self, value): 

if value is None: 

return '' 

elif isinstance(value, self._regex_type): 

return value.pattern 

else: 

return value 

 

 

class Dict(BaseType): 

 

"""A dictionary of values. 

 

When setting from a string, pass a json-like dict, e.g. `{"key", "value"}`. 

""" 

 

def __init__(self, keytype, valtype, *, fixed_keys=None, 

required_keys=None, none_ok=False): 

super().__init__(none_ok) 

# If the keytype is not a string, we'll get problems with showing it as 

# json in to_str() as json converts keys to strings. 

assert isinstance(keytype, (String, Key)), keytype 

self.keytype = keytype 

self.valtype = valtype 

self.fixed_keys = fixed_keys 

self.required_keys = required_keys 

 

def _validate_keys(self, value): 

if (self.fixed_keys is not None and not 

set(value.keys()).issubset(self.fixed_keys)): 

raise configexc.ValidationError( 

value, "Expected keys {}".format(self.fixed_keys)) 

 

if (self.required_keys is not None and not 

set(self.required_keys).issubset(value.keys())): 

raise configexc.ValidationError( 

value, "Required keys {}".format(self.required_keys)) 

 

def from_str(self, value): 

self._basic_str_validation(value) 

if not value: 

return None 

 

try: 

yaml_val = utils.yaml_load(value) 

except yaml.YAMLError as e: 

raise configexc.ValidationError(value, str(e)) 

 

# For the values, we actually want to call to_py, as we did parse them 

# from YAML, so they are numbers/booleans/... already. 

self.to_py(yaml_val) 

return yaml_val 

 

def from_obj(self, value): 

if value is None: 

return {} 

return value 

 

def _fill_fixed_keys(self, value): 

"""Fill missing fixed keys with a None-value.""" 

if self.fixed_keys is None: 

return value 

for key in self.fixed_keys: 

if key not in value: 

value[key] = self.valtype.to_py(None) 

return value 

 

def to_py(self, value): 

self._basic_py_validation(value, dict) 

if not value: 

return self._fill_fixed_keys({}) 

 

self._validate_keys(value) 

for key, val in value.items(): 

self._validate_surrogate_escapes(value, key) 

self._validate_surrogate_escapes(value, val) 

 

d = {self.keytype.to_py(key): self.valtype.to_py(val) 

for key, val in value.items()} 

return self._fill_fixed_keys(d) 

 

def to_str(self, value): 

if not value: 

# An empty Dict is treated just like None -> empty string 

return '' 

return json.dumps(value) 

 

def to_doc(self, value, indent=0): 

if not value: 

return 'empty' 

lines = ['\n'] 

prefix = '-' if not indent else '*' * indent 

for key, val in sorted(value.items()): 

lines += ('{} {}: {}'.format( 

prefix, 

self.keytype.to_doc(key), 

self.valtype.to_doc(val, indent=indent+1), 

)).splitlines() 

return '\n'.join(line.rstrip(' ') for line in lines) 

 

 

class File(BaseType): 

 

"""A file on the local filesystem.""" 

 

def __init__(self, required=True, **kwargs): 

super().__init__(**kwargs) 

self.required = required 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

value = os.path.expanduser(value) 

value = os.path.expandvars(value) 

try: 

if not os.path.isabs(value): 

value = os.path.join(standarddir.config(), value) 

 

if self.required and not os.path.isfile(value): 

raise configexc.ValidationError( 

value, 

"Must be an existing file (absolute or relative to the " 

"config directory)!") 

except UnicodeEncodeError as e: 

raise configexc.ValidationError(value, e) 

 

return value 

 

 

class Directory(BaseType): 

 

"""A directory on the local filesystem.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

value = os.path.expandvars(value) 

value = os.path.expanduser(value) 

try: 

if not os.path.isdir(value): 

raise configexc.ValidationError( 

value, "must be a valid directory!") 

if not os.path.isabs(value): 

raise configexc.ValidationError( 

value, "must be an absolute path!") 

except UnicodeEncodeError as e: 

raise configexc.ValidationError(value, e) 

 

return value 

 

 

class FormatString(BaseType): 

 

"""A string with placeholders.""" 

 

def __init__(self, fields, none_ok=False): 

super().__init__(none_ok) 

self.fields = fields 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

try: 

value.format(**{k: '' for k in self.fields}) 

except (KeyError, IndexError) as e: 

raise configexc.ValidationError(value, "Invalid placeholder " 

"{}".format(e)) 

except ValueError as e: 

raise configexc.ValidationError(value, str(e)) 

 

return value 

 

 

class ShellCommand(List): 

 

"""A shell command as a list. 

 

See the documentation for `List`. 

 

Attributes: 

placeholder: If there should be a placeholder. 

""" 

 

_show_valtype = False 

 

def __init__(self, placeholder=False, none_ok=False): 

super().__init__(valtype=String(), none_ok=none_ok) 

self.placeholder = placeholder 

 

def to_py(self, value): 

value = super().to_py(value) 

if not value: 

return value 

 

if (self.placeholder and 

'{}' not in ' '.join(value) and 

'{file}' not in ' '.join(value)): 

raise configexc.ValidationError(value, "needs to contain a " 

"{}-placeholder or a " 

"{file}-placeholder.") 

return value 

 

 

class Proxy(BaseType): 

 

"""A proxy URL, or `system`/`none`.""" 

 

def __init__(self, none_ok=False): 

super().__init__(none_ok) 

self.valid_values = ValidValues( 

('system', "Use the system wide proxy."), 

('none', "Don't use any proxy")) 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

try: 

if value == 'system': 

return SYSTEM_PROXY 

 

if value == 'none': 

url = QUrl('direct://') 

else: 

# If we add a special value to valid_values, we need to handle 

# it here! 

assert value not in self.valid_values, value 

url = QUrl(value) 

return urlutils.proxy_from_url(url) 

except (urlutils.InvalidUrlError, urlutils.InvalidProxyTypeError) as e: 

raise configexc.ValidationError(value, e) 

 

def complete(self): 

out = [] 

for val in self.valid_values: 

out.append((val, self.valid_values.descriptions[val])) 

out.append(('http://', 'HTTP proxy URL')) 

out.append(('socks://', 'SOCKS proxy URL')) 

out.append(('socks://localhost:9050/', 'Tor via SOCKS')) 

out.append(('http://localhost:8080/', 'Local HTTP proxy')) 

out.append(('pac+https://example.com/proxy.pac', 'Proxy autoconfiguration file URL')) 

return out 

 

 

class SearchEngineUrl(BaseType): 

 

"""A search engine URL.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

if not ('{}' in value or '{0}' in value): 

raise configexc.ValidationError(value, "must contain \"{}\"") 

 

try: 

value.format("") 

except (KeyError, IndexError) as e: 

raise configexc.ValidationError( 

value, "may not contain {...} (use {{ and }} for literal {/})") 

except ValueError as e: 

raise configexc.ValidationError(value, str(e)) 

 

url = QUrl(value.replace('{}', 'foobar')) 

if not url.isValid(): 

raise configexc.ValidationError( 

value, "invalid url, {}".format(url.errorString())) 

 

return value 

 

 

class FuzzyUrl(BaseType): 

 

"""A URL which gets interpreted as search if needed.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

try: 

return urlutils.fuzzy_url(value, do_search=False) 

except urlutils.InvalidUrlError as e: 

raise configexc.ValidationError(value, str(e)) 

 

 

@attr.s 

class PaddingValues: 

 

"""Four padding values.""" 

 

top = attr.ib() 

bottom = attr.ib() 

left = attr.ib() 

right = attr.ib() 

 

 

class Padding(Dict): 

 

"""Setting for paddings around elements.""" 

 

_show_valtype = False 

 

def __init__(self, none_ok=False): 

super().__init__(keytype=String(), 

valtype=Int(minval=0, none_ok=none_ok), 

fixed_keys=['top', 'bottom', 'left', 'right'], 

none_ok=none_ok) 

 

def to_py(self, value): 

d = super().to_py(value) 

return PaddingValues(**d) 

 

 

class Encoding(BaseType): 

 

"""Setting for a python encoding.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

try: 

codecs.lookup(value) 

except LookupError: 

raise configexc.ValidationError(value, "is not a valid encoding!") 

return value 

 

 

class Position(MappingType): 

 

"""The position of the tab bar.""" 

 

MAPPING = { 

'top': QTabWidget.North, 

'bottom': QTabWidget.South, 

'left': QTabWidget.West, 

'right': QTabWidget.East, 

} 

 

def __init__(self, none_ok=False): 

super().__init__( 

none_ok, 

valid_values=ValidValues('top', 'bottom', 'left', 'right')) 

 

 

class TextAlignment(MappingType): 

 

"""Alignment of text.""" 

 

MAPPING = { 

'left': Qt.AlignLeft, 

'right': Qt.AlignRight, 

'center': Qt.AlignCenter, 

} 

 

def __init__(self, none_ok=False): 

super().__init__( 

none_ok, 

valid_values=ValidValues('left', 'right', 'center')) 

 

 

class VerticalPosition(String): 

 

"""The position of the download bar.""" 

 

def __init__(self, none_ok=False): 

super().__init__(none_ok=none_ok) 

self.valid_values = ValidValues('top', 'bottom') 

 

 

class Url(BaseType): 

 

"""A URL as a string.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

qurl = QUrl.fromUserInput(value) 

if not qurl.isValid(): 

raise configexc.ValidationError(value, "invalid URL - " 

"{}".format(qurl.errorString())) 

return qurl 

 

 

class SessionName(BaseType): 

 

"""The name of a session.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

if value.startswith('_'): 

raise configexc.ValidationError(value, "may not start with '_'!") 

return value 

 

 

class SelectOnRemove(MappingType): 

 

"""Which tab to select when the focused tab is removed.""" 

 

MAPPING = { 

'prev': QTabBar.SelectLeftTab, 

'next': QTabBar.SelectRightTab, 

'last-used': QTabBar.SelectPreviousTab, 

} 

 

def __init__(self, none_ok=False): 

super().__init__( 

none_ok, 

valid_values=ValidValues( 

('prev', "Select the tab which came before the closed one " 

"(left in horizontal, above in vertical)."), 

('next', "Select the tab which came after the closed one " 

"(right in horizontal, below in vertical)."), 

('last-used', "Select the previously selected tab."))) 

 

 

class ConfirmQuit(FlagList): 

 

"""Whether to display a confirmation when the window is closed.""" 

 

# Values that can be combined with commas 

combinable_values = ('multiple-tabs', 'downloads') 

 

def __init__(self, none_ok=False): 

super().__init__(none_ok) 

self.valtype.none_ok = none_ok 

self.valtype.valid_values = ValidValues( 

('always', "Always show a confirmation."), 

('multiple-tabs', "Show a confirmation if " 

"multiple tabs are opened."), 

('downloads', "Show a confirmation if " 

"downloads are running"), 

('never', "Never show a confirmation.")) 

 

def to_py(self, value): 

values = super().to_py(value) 

if not values: 

return values 

 

# Never can't be set with other options 

if 'never' in values and len(values) > 1: 

raise configexc.ValidationError( 

values, "List cannot contain never!") 

# Always can't be set with other options 

elif 'always' in values and len(values) > 1: 

raise configexc.ValidationError( 

values, "List cannot contain always!") 

 

return values 

 

 

class NewTabPosition(String): 

 

"""How new tabs are positioned.""" 

 

def __init__(self, none_ok=False): 

super().__init__(none_ok=none_ok) 

self.valid_values = ValidValues( 

('prev', "Before the current tab."), 

('next', "After the current tab."), 

('first', "At the beginning."), 

('last', "At the end.")) 

 

 

class TimestampTemplate(BaseType): 

 

"""An strftime-like template for timestamps. 

 

See 

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior 

for reference. 

""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

 

try: 

# Dummy check to see if the template is valid 

datetime.datetime.now().strftime(value) 

except ValueError as error: 

# thrown on invalid template string 

raise configexc.ValidationError( 

value, "Invalid format string: {}".format(error)) 

 

return value 

 

 

class Key(BaseType): 

 

"""A name of a key.""" 

 

def to_py(self, value): 

self._basic_py_validation(value, str) 

if not value: 

return None 

if utils.is_special_key(value): 

value = '<{}>'.format(utils.normalize_keystr(value[1:-1])) 

return value