-
-
Notifications
You must be signed in to change notification settings - Fork 766
Expand file tree
/
Copy path__init__.py
More file actions
1550 lines (1374 loc) · 51.6 KB
/
__init__.py
File metadata and controls
1550 lines (1374 loc) · 51.6 KB
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
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2006-2026 NV Access Limited, Aleksey Sadovoy, Peter Vágner, Rui Batista, Zahari Yurukov,
# Joseph Lee, Babbage B.V., Łukasz Golonka, Julien Cochuyt, Cyrille Bougot
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
"""Manages NVDA configuration.
The heart of NVDA's configuration is Configuration Manager, which records current options, profile information and functions to load, save, and switch amongst configuration profiles.
In addition, this module provides three actions: profile switch notifier, an action to be performed when NVDA saves settings, and action to be performed when NVDA is asked to reload configuration from disk or reset settings to factory defaults.
For the latter two actions, one can perform actions prior to and/or after they take place.
"""
from collections.abc import Collection
from enum import Enum
from typing import Any
import globalVars
import winreg
import os
import sys
import errno
import itertools
import contextlib
from copy import deepcopy
from collections import OrderedDict
from configobj import ConfigObj
from configobj.validate import Validator
from logHandler import log
import logging
from utils.caseInsensitiveCollections import CaseInsensitiveSet
import winBindings.shell32
from shlobj import FolderId, SHGetKnownFolderPath
import baseObject
import easeOfAccess
from fileUtils import FaultTolerantFile
import extensionPoints
import functools
from . import profileUpgrader
from . import aggregatedSection
from .configSpec import confspec
from .featureFlag import (
_transformSpec_AddFeatureFlagDefault,
_validateConfig_featureFlag,
)
from .registry import RegistryKey as _RegistryKey
import NVDAState
from NVDAState import WritePaths
#: True if NVDA is running as a Windows Store Desktop Bridge application
isAppX = False
#: The active configuration, C{None} if it has not yet been loaded.
#: @type: ConfigManager
conf = None
#: Notifies after the configuration profile has been switched.
#: This allows components and add-ons to apply changes required by the new configuration.
#: For example, braille switches braille displays if necessary.
#: Handlers are called with no arguments.
post_configProfileSwitch = extensionPoints.Action()
#: Notifies when NVDA is saving current configuration.
#: Handlers can listen to "pre" and/or "post" action to perform tasks prior to and/or after NVDA's own configuration is saved.
#: Handlers are called with no arguments.
pre_configSave = extensionPoints.Action()
post_configSave = extensionPoints.Action()
#: Notifies when configuration is reloaded from disk or factory defaults are applied.
#: Handlers can listen to "pre" and/or "post" action to perform tasks prior to and/or after NVDA's own configuration is reloaded.
#: Handlers are called with a boolean argument indicating whether this is a factory reset (True) or just reloading from disk (False).
pre_configReset = extensionPoints.Action()
post_configReset = extensionPoints.Action()
def __getattr__(attrName: str) -> Any:
"""Module level `__getattr__` used to preserve backward compatibility."""
if attrName == "RegistryKey" and NVDAState._allowDeprecatedAPI():
log.warning("Importing RegistryKey from here is deprecated, use config.registry.RegistryKey instead.")
return _RegistryKey
if attrName == "NVDA_REGKEY" and NVDAState._allowDeprecatedAPI():
log.warning("NVDA_REGKEY is deprecated, use RegistryKey.NVDA instead.")
return _RegistryKey.NVDA.value
if attrName == "RUN_REGKEY" and NVDAState._allowDeprecatedAPI():
log.warning("RUN_REGKEY is deprecated, use RegistryKey.RUN instead.")
return _RegistryKey.RUN.value
if attrName == "addConfigDirsToPythonPackagePath" and NVDAState._allowDeprecatedAPI():
log.warning(
"addConfigDirsToPythonPackagePath is deprecated, "
"use addonHandler.packaging.addDirsToPythonPackagePath instead.",
)
from addonHandler.packaging import addDirsToPythonPackagePath
return addDirsToPythonPackagePath
if attrName == "CONFIG_IN_LOCAL_APPDATA_SUBKEY" and NVDAState._allowDeprecatedAPI():
# Note: this should only log in situations where it will not be excessively noisy.
log.warning(
"CONFIG_IN_LOCAL_APPDATA_SUBKEY is deprecated. "
"Instead use RegistryKey.CONFIG_IN_LOCAL_APPDATA_SUBKEY. ",
stack_info=True,
)
return _RegistryKey.CONFIG_IN_LOCAL_APPDATA_SUBKEY.value
raise AttributeError(f"module {repr(__name__)} has no attribute {repr(attrName)}")
def initialize():
global conf
conf = ConfigManager()
def saveOnExit():
"""Save the configuration if configured to save on exit.
This should only be called if NVDA is about to exit.
Errors are ignored.
"""
if conf["general"]["saveConfigurationOnExit"]:
try:
conf.save()
except: # noqa: E722
pass
def isInstalledCopy() -> bool:
"""Checks to see if this running copy of NVDA is installed on the system"""
try:
k = winreg.OpenKey(
winreg.HKEY_LOCAL_MACHINE,
_RegistryKey.INSTALLED_COPY.value,
)
except FileNotFoundError:
log.debug(
f"Unable to find isInstalledCopy registry key {_RegistryKey.INSTALLED_COPY}"
"- this is not an installed copy.",
)
return False
except WindowsError:
log.error(
f"Unable to open isInstalledCopy registry key {_RegistryKey.INSTALLED_COPY}",
exc_info=True,
)
return False
try:
instDir = winreg.QueryValueEx(k, "UninstallDirectory")[0]
except FileNotFoundError:
log.debug(
f"Unable to find UninstallDirectory value for {_RegistryKey.INSTALLED_COPY}"
"- this may not be an installed copy.",
)
return False
except WindowsError:
log.error("Unable to query isInstalledCopy registry key", exc_info=True)
return False
k.Close()
try:
return os.stat(instDir) == os.stat(globalVars.appDir)
except (WindowsError, FileNotFoundError):
log.error(
"Failed to access the installed NVDA directory,"
"or, a portable copy failed to access the current NVDA app directory",
exc_info=True,
)
return False
def getInstalledUserConfigPath() -> str | None:
try:
winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _RegistryKey.NVDA.value)
except FileNotFoundError:
log.debug("Could not find nvda registry key, NVDA is not currently installed")
return None
except WindowsError:
log.error("Could not open nvda registry key", exc_info=True)
return None
if NVDAState._configInLocalAppDataEnabled():
configFolder = FolderId.LOCAL_APP_DATA
else:
configFolder = FolderId.ROAMING_APP_DATA
configParent = SHGetKnownFolderPath(configFolder)
try:
return os.path.join(configParent, "nvda")
except WindowsError:
# (#13242) There is some uncertainty as to how this could be caused
log.debugWarning("Installed user config is not in local app data", exc_info=True)
return None
def getUserDefaultConfigPath(useInstalledPathIfExists=False):
"""Get the default path for the user configuration directory.
This is the default path and doesn't reflect overriding from the command line,
which includes temporary copies.
Most callers will want the C{NVDAState.WritePaths.configDir variable} instead.
"""
installedUserConfigPath = getInstalledUserConfigPath()
if installedUserConfigPath and (
isInstalledCopy() or isAppX or (useInstalledPathIfExists and os.path.isdir(installedUserConfigPath))
):
if isAppX:
# NVDA is running as a Windows Store application.
# Although Windows will redirect %APPDATA% to a user directory specific to the Windows Store application,
# It also makes existing %APPDATA% files available here.
# We cannot share NVDA user config directories with other copies of NVDA as their config may be using add-ons
# Therefore add a suffix to the directory to make it specific to Windows Store application versions.
installedUserConfigPath += "_appx"
return installedUserConfigPath
return os.path.join(globalVars.appDir, "userConfig")
SCRATCH_PAD_ONLY_DIRS = (
"appModules",
"brailleDisplayDrivers",
"brailleTables",
"globalPlugins",
"synthDrivers",
"visionEnhancementProviders",
)
def getScratchpadDir(ensureExists: bool = False) -> str:
"""Returns the path where custom appModules, globalPlugins and drivers can be placed while being developed."""
path = WritePaths.scratchpadDir
if ensureExists:
if not os.path.isdir(path):
os.makedirs(path)
for subdir in SCRATCH_PAD_ONLY_DIRS:
subpath = os.path.join(path, subdir)
if not os.path.isdir(subpath):
os.makedirs(subpath)
return path
def initConfigPath(configPath: str | None = None) -> None:
"""
Creates the current configuration path if it doesn't exist. Also makes sure that various sub directories also exist.
:param configPath: an optional path which should be used instead (only useful when being called from outside of NVDA)
"""
if not configPath:
configPath = WritePaths.configDir
if not os.path.isdir(configPath):
os.makedirs(configPath)
else:
OLD_CODE_DIRS = ("appModules", "brailleDisplayDrivers", "globalPlugins", "synthDrivers")
# #10014: Since #9238 code from these directories is no longer loaded.
# However they still exist in config for older installations. Remove them if empty to minimize confusion.
for dir in OLD_CODE_DIRS:
dir = os.path.join(configPath, dir)
if os.path.isdir(dir):
try:
os.rmdir(dir)
log.info("Removed old plugins dir: %s", dir)
except OSError as ex:
if ex.errno == errno.ENOTEMPTY:
log.info("Failed to remove old plugins dir: %s. Directory not empty.", dir)
subdirs = ["speechDicts", "profiles"]
if not isAppX:
subdirs.append("addons")
for subdir in subdirs:
subdir = os.path.join(configPath, subdir)
if not os.path.isdir(subdir):
os.makedirs(subdir)
def getStartAfterLogon() -> bool:
"""Not to be confused with getStartOnLogonScreen.
Checks if NVDA is set to start after a logon.
Checks related easeOfAccess current user registry keys.
"""
return easeOfAccess.willAutoStart(easeOfAccess.AutoStartContext.AFTER_LOGON)
def setStartAfterLogon(enable: bool) -> None:
"""Not to be confused with setStartOnLogonScreen.
Toggle if NVDA automatically starts after a logon.
Sets easeOfAccess related registry keys.
"""
if getStartAfterLogon() == enable:
return
easeOfAccess.setAutoStart(easeOfAccess.AutoStartContext.AFTER_LOGON, enable)
SLAVE_FILENAME = os.path.join(globalVars.appDir, "nvda_slave.exe")
def getStartOnLogonScreen() -> bool:
"""Not to be confused with getStartAfterLogon.
Checks if NVDA is set to start on the logon screen.
Checks related easeOfAccess local machine registry keys.
"""
return easeOfAccess.willAutoStart(easeOfAccess.AutoStartContext.ON_LOGON_SCREEN)
def _setStartOnLogonScreen(enable: bool) -> None:
easeOfAccess.setAutoStart(easeOfAccess.AutoStartContext.ON_LOGON_SCREEN, enable)
def setSystemConfigToCurrentConfig(*, addonsToCopy: Collection[str] = ()):
"""
Replaces the system configuration with the current user configuration.
:param addonsToCopy: IDs of the add-ons to copy, defaults to ()
.. warning::
Only enabled add-ons should be copied.
Providing IDs of add-ons that are disabled may cause unexpected results,
especially for add-ons that are not compatible with the current API version.
:raises installer.RetriableFailure: If copying the user to the system config fails.
:raises RuntimeError: If calling ``nvda_slave`` fails for some other reason.
"""
fromPath = WritePaths.configDir
if winBindings.shell32.IsUserAnAdmin():
_setSystemConfig(fromPath, addonsToCopy=addonsToCopy)
else:
import systemUtils
res = systemUtils.execElevated(
SLAVE_FILENAME,
("setNvdaSystemConfig", fromPath, *addonsToCopy),
wait=True,
)
if res == 2:
import installer
raise installer.RetriableFailure
elif res != 0:
raise RuntimeError("Slave failure")
def _setSystemConfig(
fromPath: str,
*,
prefix: str = sys.prefix,
addonsToCopy: Collection[str] = (),
isMigration: bool = False,
):
"""
Sets the system config to that in ``fromPath``.
:param fromPath: Path to config directory to copy.
:param prefix: Directory in which to set the system config, defaults to :attr:`sys.prefix`.
The system config will be in a ``systemConfig`` subdirectory of this directory.
:param addonsToCopy: List of add-on IDs to include in the system configuration, defaults to `()`.
:param isMigration: Whether this is a migration from one system config location to another, defaults to ``False``.
When this is ``True``, the ``addons/`` directory and ``addonsState.pickle``/``addonsState.json`` in ``fromPath`` will be copied as-is, if they exist.
"""
import installer
import addonHandler
toPath = os.path.join(prefix, "systemConfig")
log.debug("Copying config to systemconfig dir: %s", toPath)
if os.path.isdir(toPath):
installer.tryRemoveFile(toPath)
for curSourceDir, subDirs, files in os.walk(fromPath):
if curSourceDir == fromPath:
curDestDir = toPath
# Don't copy from top-level config dirs we know will be ignored due to security risks.
removeSubs = set(SCRATCH_PAD_ONLY_DIRS).intersection(subDirs)
for subPath in removeSubs:
log.debug("Ignored folder that may contain unpackaged addons: %s", subPath)
subDirs.remove(subPath)
if not isMigration:
# Don't copy the addons state file,
# as we will generate a new one based on which add-ons are being copied.
# Just in case it still exists, also exclude the old one.
stateFilenames = (
addonHandler.STATE_FILENAME.casefold(),
addonHandler._OLD_STATE_FILENAME.casefold(),
)
files = [filename for filename in files if filename.casefold() not in stateFilenames]
else:
relativePath = os.path.relpath(curSourceDir, fromPath)
curDestDir = os.path.join(toPath, relativePath)
if not isMigration and relativePath == "addons":
_prepareToCopyAddons(fromPath, toPath, subDirs, addonsToCopy)
if not os.path.isdir(curDestDir):
os.makedirs(curDestDir)
for f in files:
# Do not copy executables to the system configuration, as this may cause security risks.
# This will also exclude pending updates.
if f.casefold().endswith(".exe"):
log.debug(
"Ignored file %s while copying current user configuration to system configuration" % f,
)
continue
sourceFilePath = os.path.join(curSourceDir, f)
destFilePath = os.path.join(curDestDir, f)
installer.tryCopyFile(sourceFilePath, destFilePath)
def _prepareToCopyAddons(fromPath: str, toPath: str, addonDirs: list[str], addonsToCopy: Collection[str]):
"""Determine which add-on directories to copy to the system profile, and create the appropriate addonsState file.
.. Note::
While this function returns ``None``, it has two major side-effects:
1. The ``addonDirs`` list is mutated to contain only the add-ons that should be copied.
2. A new `addonsState.pickle` is created in ``toPath``.
:param fromPath: Root of the source configuration directory.
:param toPath: Root of the destination configuration directory
:param addonDirs: Subdirectories of ``addons/`` in ``fromPath``.
This will be mutated to only contain the add-ons that should be copied.
:param addonsToCopy: Add-on IDs of the add-ons that should be copied.
"""
from addonStore.models.status import AddonStateCategory
import addonHandler
addonsToCopy = CaseInsensitiveSet(addonsToCopy)
allAddons = addonDirs[:]
addonDirs.clear()
addonDirs.extend(addon for addon in allAddons if addon.casefold() in addonsToCopy)
if addonDirs:
log.debug(f"Copying add-ons: {', '.join(addonDirs)}")
# We are copying add-ons, so we need to generate a new addons state file.
# If no add-ons have their compatibility overridden, the file will not be saved, but this is fine.
userAddonsState = addonHandler.AddonsState()
userAddonsState._load(os.path.join(fromPath, addonHandler.STATE_FILENAME))
systemAddonsState = addonHandler.AddonsState()
systemAddonsState.manualOverridesAPIVersion = userAddonsState.manualOverridesAPIVersion
systemAddonsState[AddonStateCategory.OVERRIDE_COMPATIBILITY] = (
userAddonsState[AddonStateCategory.OVERRIDE_COMPATIBILITY] & addonsToCopy
)
systemAddonsState._save(statePath=os.path.join(toPath, addonHandler.STATE_FILENAME))
else:
log.debug("No add-ons to copy.")
def setStartOnLogonScreen(enable: bool) -> None:
"""
Not to be confused with setStartAfterLogon.
Toggle whether NVDA starts on the logon screen automatically.
On failure to set, retries with escalated permissions.
Raises a RuntimeError on failure.
"""
if getStartOnLogonScreen() == enable:
return
try:
# Try setting it directly.
_setStartOnLogonScreen(enable)
except WindowsError:
log.debugWarning(
"Failed to set start on logon screen's config, retrying elevated.",
exc_info=True,
)
# We probably don't have admin privs, so we need to elevate to do this using the slave.
import systemUtils
if (
systemUtils.execElevated(
SLAVE_FILENAME,
("config_setStartOnLogonScreen", "%d" % enable),
wait=True,
)
!= 0
):
raise RuntimeError("Slave failed to set startOnLogonScreen")
def _transformSpec(spec: ConfigObj):
"""To make the spec less verbose, transform the spec:
- Add default="default" to all featureFlag items. This is required so that the key can be read,
even if it is missing from the config.
"""
spec.configspec = spec
spec.validate(
Validator(
{
"featureFlag": _transformSpec_AddFeatureFlagDefault,
},
),
preserve_errors=True,
)
class ConfigManager:
"""Manages and provides access to configuration.
In addition to the base configuration, there can be multiple active configuration profiles.
Settings in more recently activated profiles take precedence,
with the base configuration being consulted last.
This allows a profile to override settings in profiles activated earlier and the base configuration.
A profile need only include a subset of the available settings.
Changed settings are written to the most recently activated profile.
"""
BASE_ONLY_SECTIONS = {
"general",
"update",
"development",
"addonStore",
"remote",
"math",
"screenCurtain",
}
"""
Sections that only apply to the base configuration;
i.e. they cannot be overridden in profiles.
Note this set may be extended by add-ons.
"""
def __init__(self):
self.spec = confspec
_transformSpec(self.spec)
#: All loaded profiles by name.
self._profileCache: dict[str | None, ConfigObj] = {}
#: The active profiles.
self.profiles: list[ConfigObj] = []
#: Whether profile triggers are enabled (read-only).
self.profileTriggersEnabled: bool = True
self.validator: Validator = Validator(
{
"_featureFlag": _validateConfig_featureFlag,
},
)
self.rootSection: AggregatedSection | None = None
self._shouldHandleProfileSwitch: bool = True
self._pendingHandleProfileSwitch: bool = False
self._suspendedTriggers: list[ProfileTrigger] | None = None
self._initBaseConf()
#: Maps triggers to profiles.
self.triggersToProfiles: dict[ProfileTrigger, ConfigObj] | None = None
self._loadProfileTriggers()
#: The names of all profiles that have been modified since they were last saved.
self._dirtyProfiles: set[str] = set()
def _handleProfileSwitch(self, shouldNotify=True):
if not self._shouldHandleProfileSwitch:
self._pendingHandleProfileSwitch = True
return
currentRootSection = self.rootSection
init = currentRootSection is None
# Reset the cache.
self.rootSection = AggregatedSection(self, (), self.spec, self.profiles)
if init:
# We're still initialising, so don't notify anyone about this change.
return
if shouldNotify:
post_configProfileSwitch.notify(prevConf=currentRootSection.dict())
def _initBaseConf(self, factoryDefaults=False):
fn = WritePaths.nvdaConfigFile
if factoryDefaults:
profile = self._loadConfig(None)
profile.filename = fn
else:
try:
profile = self._loadConfig(fn) # a blank config returned if fn does not exist
self.baseConfigError = False
except: # noqa: E722
backupFileName = fn + ".corrupted.bak"
log.error(
"Error loading base configuration; the base configuration file will be reinitialized."
f" A copy of your previous configuration file will be saved at {backupFileName}",
exc_info=True,
)
try:
if os.path.exists(backupFileName):
os.unlink(backupFileName)
os.rename(fn, backupFileName)
except Exception:
log.error(
f"Unable to save a copy of the corrupted configuration to {backupFileName}",
exc_info=True,
)
self.baseConfigError = True
return self._initBaseConf(factoryDefaults=True)
for key in self.BASE_ONLY_SECTIONS:
# These sections are returned directly from the base config, so validate them here.
try:
sect = profile[key]
except KeyError:
profile[key] = {}
# ConfigObj mutates this into a configobj.Section.
sect = profile[key]
sect.configspec = self.spec[key]
profile.validate(self.validator, section=sect)
self._profileCache[None] = profile
self.profiles.append(profile)
self._handleProfileSwitch()
@staticmethod
def _shouldLogConfigAtStartup(profile: ConfigObj) -> bool:
"""since profile settings are not yet imported we have to "peek" to see
if debug level logging is enabled.
:param profile: The profile to check for logging settings.
:return: True if debug level logging is enabled, False otherwise.
"""
#
try:
logLevelName: str = profile["general"]["loggingLevel"]
if not logLevelName:
level = None
else:
level = logging.getLevelNamesMapping().get(logLevelName)
except KeyError:
level = None
return log.isEnabledFor(log.DEBUG) or (level and logging.DEBUG >= level)
def _loadConfig(self, fn: str | None, fileError: bool = False) -> ConfigObj:
"""Load a configuration from a file.
:param fn: The filename of the configuration file to load.
:param fileError: Whether to raise an error if the file cannot be read, defaults to False
:raises e: Re-raises any exception that occurs during the profile upgrade process.
:return: The loaded configuration object.
"""
log.info("Loading config: {0}".format(fn))
profile = ConfigObj(fn, indent_type="\t", encoding="UTF-8", file_error=fileError)
# Python converts \r\n to \n when reading files in Windows, so ConfigObj can't determine the true line ending.
profile.newlines = "\r\n"
profileCopy = deepcopy(profile)
if NVDAState.shouldWriteToDisk() and profile.filename is not None:
writeProfileFunc = self._writeProfileToFile
else:
writeProfileFunc = None
try:
profileUpgrader.upgrade(profile, self.validator, writeProfileFunc)
except Exception as e:
if self._shouldLogConfigAtStartup(profileCopy):
# We must log at info level here as the logHandler hasn't been set to log at debug level yet.
log.info(f"Config before schema update:\n{profileCopy}", redactSecrets=True)
raise e
if self._shouldLogConfigAtStartup(profile):
# We must log at info level here as the logHandler hasn't been set to log at debug level yet.
log.info(
f"Config loaded (after upgrade, and in the state it will be used by NVDA):\n{profile}",
redactSecrets=True,
)
return profile
def __getitem__(self, key):
if key in self.BASE_ONLY_SECTIONS:
# Return these directly from the base configuration.
return self.profiles[0][key]
return self.rootSection[key]
def __contains__(self, key):
return key in self.rootSection
def get(self, key, default=None):
return self.rootSection.get(key, default)
def __setitem__(self, key, val):
self.rootSection[key] = val
def dict(self):
return self.rootSection.dict()
def listProfiles(self):
try:
profileFiles = os.listdir(WritePaths.profilesDir)
except FileNotFoundError:
log.debugWarning("Profiles directory does not exist.")
profileFiles = []
for name in profileFiles:
name, ext = os.path.splitext(name)
if ext == ".ini":
yield name
def _getProfileFn(self, name: str) -> str:
return WritePaths.getProfileConfigFile(name)
def _getProfile(self, name, load=True):
try:
return self._profileCache[name]
except KeyError:
if not load:
raise KeyError(name)
# Load the profile.
fn = self._getProfileFn(name)
profile = self._loadConfig(fn, fileError=True) # file must exist.
profile.name = name
profile.manual = False
profile.triggered = False
self._profileCache[name] = profile
return profile
def getProfile(self, name):
"""Get a profile given its name.
This is useful for checking whether a profile has been manually activated or triggered.
@param name: The name of the profile.
@type name: str
@return: The profile object.
@raise KeyError: If the profile is not loaded.
"""
return self._getProfile(name, load=False)
def manualActivateProfile(self, name):
"""Manually activate a profile.
Only one profile can be manually active at a time.
If another profile was manually activated, deactivate it first.
If C{name} is C{None}, a profile will not be activated.
@param name: The name of the profile or C{None} for no profile.
@type name: str
"""
if len(self.profiles) > 1:
profile = self.profiles[-1]
if profile.manual:
del self.profiles[-1]
profile.manual = False
if name:
profile = self._getProfile(name)
profile.manual = True
self.profiles.append(profile)
self._handleProfileSwitch()
def _markWriteProfileDirty(self):
if len(self.profiles) == 1:
# There's nothing other than the base config, which is always saved anyway.
return
self._dirtyProfiles.add(self.profiles[-1].name)
def _writeProfileToFile(self, filename: str, profile: ConfigObj):
with FaultTolerantFile(filename) as f:
profile.write(f)
def save(self):
"""Save all modified profiles and the base configuration to disk."""
# #7598: give others a chance to either save settings early or terminate tasks.
pre_configSave.notify()
if not NVDAState.shouldWriteToDisk():
log.info("Not writing profile, either --secure or --launcher args present")
return
try:
self._writeProfileToFile(self.profiles[0].filename, self.profiles[0])
log.info("Base configuration saved")
for name in self._dirtyProfiles:
self._writeProfileToFile(self._profileCache[name].filename, self._profileCache[name])
log.info("Saved configuration profile %s" % name)
self._dirtyProfiles.clear()
except PermissionError as e:
log.warning("Error saving configuration; probably read only file system", exc_info=True)
raise e
except Exception as e:
log.warning("Error saving configuration", exc_info=True)
raise e
post_configSave.notify()
def reset(self, factoryDefaults=False):
"""Reset the configuration to saved settings or factory defaults.
@param factoryDefaults: C{True} to reset to factory defaults, C{False} to reset to saved configuration.
@type factoryDefaults: bool
"""
pre_configReset.notify(factoryDefaults=factoryDefaults)
self.profiles = []
self._profileCache.clear()
self._dirtyProfiles.clear()
# Signal that we're initialising.
self.rootSection = None
self._initBaseConf(factoryDefaults=factoryDefaults)
post_configReset.notify(factoryDefaults=factoryDefaults)
def createProfile(self, name):
"""Create a profile.
@param name: The name of the profile to create.
@type name: str
@raise ValueError: If a profile with this name already exists.
"""
if not NVDAState.shouldWriteToDisk():
log.debug("Not creating configuration profile, as shouldWriteToDisk returned False.")
return
if not name:
raise ValueError("Missing name.")
fn = self._getProfileFn(name)
if os.path.isfile(fn):
raise ValueError("A profile with the same name already exists: %s" % name)
# Just create an empty file to make sure we can.
open(fn, "w").close()
# Register a script for the new profile.
# Import late to avoid circular import.
from globalCommands import ConfigProfileActivationCommands
ConfigProfileActivationCommands.addScriptForProfile(name)
def deleteProfile(self, name):
"""Delete a profile.
@param name: The name of the profile to delete.
@type name: str
@raise LookupError: If the profile doesn't exist.
"""
if not NVDAState.shouldWriteToDisk():
log.debug("Not deleting profile, as shouldSaveToDisk returned False.")
return
fn = self._getProfileFn(name)
if not os.path.isfile(fn):
raise LookupError("No such profile: %s" % name)
os.remove(fn)
# Remove the script for the deleted profile from the script collector.
# Import late to avoid circular import.
from globalCommands import ConfigProfileActivationCommands
ConfigProfileActivationCommands.removeScriptForProfile(name)
try:
del self._profileCache[name]
except KeyError:
pass
# Remove any triggers associated with this profile.
allTriggers = self.triggersToProfiles
# You can't delete from a dict while iterating through it.
delTrigs = [trigSpec for trigSpec, trigProfile in allTriggers.items() if trigProfile == name]
if delTrigs:
for trigSpec in delTrigs:
del allTriggers[trigSpec]
self.saveProfileTriggers()
# Remove the profile from the dirty profile list
try:
self._dirtyProfiles.remove(name)
except KeyError:
# The profile wasn't dirty.
pass
# Check if this profile was active.
delProfile = None
for index in range(len(self.profiles) - 1, -1, -1):
profile = self.profiles[index]
if profile.name == name:
# Deactivate it.
del self.profiles[index]
delProfile = profile
if not delProfile:
return
self._handleProfileSwitch()
if self._suspendedTriggers:
# Remove any suspended triggers referring to this profile.
# As the dictionary changes during iteration, wrap this inside a list call.
for trigger in list(self._suspendedTriggers):
if trigger._profile == delProfile:
del self._suspendedTriggers[trigger]
def renameProfile(self, oldName, newName):
"""Rename a profile.
@param oldName: The current name of the profile.
@type oldName: str
@param newName: The new name for the profile.
@type newName: str
@raise LookupError: If the profile doesn't exist.
@raise ValueError: If a profile with the new name already exists.
"""
if not NVDAState.shouldWriteToDisk():
log.debug("Not renaming profile, as shouldWriteToDisk returned False.")
return
if newName == oldName:
return
if not newName:
raise ValueError("Missing newName")
oldFn = self._getProfileFn(oldName)
newFn = self._getProfileFn(newName)
if not os.path.isfile(oldFn):
raise LookupError("No such profile: %s" % oldName)
# Windows file names are case insensitive,
# so only test for file existence if the names don't match case insensitively.
if oldName.lower() != newName.lower() and os.path.isfile(newFn):
raise ValueError("A profile with the same name already exists: %s" % newName)
os.rename(oldFn, newFn)
# Update any associated triggers.
allTriggers = self.triggersToProfiles
saveTrigs = False
for trigSpec, trigProfile in allTriggers.items():
if trigProfile == oldName:
allTriggers[trigSpec] = newName
saveTrigs = True
if saveTrigs:
self.saveProfileTriggers()
# Rename the script for the profile.
# Import late to avoid circular import.
from globalCommands import ConfigProfileActivationCommands
ConfigProfileActivationCommands.updateScriptForRenamedProfile(oldName, newName)
try:
profile = self._profileCache.pop(oldName)
except KeyError:
# The profile hasn't been loaded, so there's nothing more to do.
return
profile.name = newName
self._profileCache[newName] = profile
try:
self._dirtyProfiles.remove(oldName)
except KeyError:
# The profile wasn't dirty.
return
self._dirtyProfiles.add(newName)
def _triggerProfileEnter(self, trigger):
"""Called by L{ProfileTrigger.enter}}}."""
if not self.profileTriggersEnabled:
return
if self._suspendedTriggers is not None:
self._suspendedTriggers[trigger] = "enter"
return
log.debug("Activating triggered profile %s" % trigger.profileName)
try:
profile = trigger._profile = self._getProfile(trigger.profileName)
except:
trigger._profile = None
raise
profile.triggered = True
if len(self.profiles) > 1 and self.profiles[-1].manual:
# There's a manually activated profile.
# Manually activated profiles must be at the top of the stack, so insert this one below.
self.profiles.insert(-1, profile)
else:
self.profiles.append(profile)
self._handleProfileSwitch(trigger._shouldNotifyProfileSwitch)
def _triggerProfileExit(self, trigger):
"""Called by L{ProfileTrigger.exit}}}."""
if not self.profileTriggersEnabled:
return
if self._suspendedTriggers is not None:
if trigger in self._suspendedTriggers:
# This trigger was entered and is now being exited.
# These cancel each other out.
del self._suspendedTriggers[trigger]
else:
self._suspendedTriggers[trigger] = "exit"
return
profile = trigger._profile
if profile is None:
return
log.debug("Deactivating triggered profile %s" % trigger.profileName)
profile.triggered = False
try:
self.profiles.remove(profile)
except ValueError:
# This is probably due to the user resetting the configuration.
log.debugWarning("Profile not active when exiting trigger")
return
self._handleProfileSwitch(trigger._shouldNotifyProfileSwitch)
@contextlib.contextmanager
def atomicProfileSwitch(self):
"""Indicate that multiple profile switches should be treated as one.
This is useful when multiple triggers may be exited/entered at once;
e.g. when switching applications.
While multiple switches aren't harmful, they might take longer;
e.g. unnecessarily switching speech synthesizers or braille displays.
This is a context manager to be used with the C{with} statement.
"""
self._shouldHandleProfileSwitch = False
try:
yield
finally:
self._shouldHandleProfileSwitch = True
if self._pendingHandleProfileSwitch:
self._handleProfileSwitch()
self._pendingHandleProfileSwitch = False
def suspendProfileTriggers(self):
"""Suspend handling of profile triggers.
Any triggers that currently apply will continue to apply.
Subsequent enters or exits will not apply until triggers are resumed.
@see: L{resumeTriggers}
"""
if self._suspendedTriggers is not None:
return
self._suspendedTriggers = OrderedDict()
def resumeProfileTriggers(self):
"""Resume handling of profile triggers after previous suspension.
Any trigger enters or exits that occurred while triggers were suspended will be applied.
Trigger handling will then return to normal.
@see: L{suspendTriggers}
"""
if self._suspendedTriggers is None:
return
triggers = self._suspendedTriggers
self._suspendedTriggers = None
with self.atomicProfileSwitch():
for trigger, action in triggers.items():
trigger.enter() if action == "enter" else trigger.exit()
def disableProfileTriggers(self):
"""Temporarily disable all profile triggers.
Any triggered profiles will be deactivated and subsequent triggers will not apply.
Call L{enableTriggers} to re-enable triggers.
"""
if not self.profileTriggersEnabled:
return
self.profileTriggersEnabled = False
for profile in self.profiles[1:]:
profile.triggered = False
if len(self.profiles) > 1 and self.profiles[-1].manual:
del self.profiles[1:-1]
else:
del self.profiles[1:]
self._suspendedTriggers = None
self._handleProfileSwitch()
def enableProfileTriggers(self):
"""Re-enable profile triggers after they were previously disabled."""