File: cache.py

package info (click to toggle)
turing 0.11-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 10,340 kB
  • sloc: python: 106,582; xml: 101; makefile: 53; sh: 29
file content (148 lines) | stat: -rw-r--r-- 4,877 bytes parent folder | download
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
"""
This module contains a class to access the pyQode settings (QSettings).

QSettings are used to cache some specific settings.

At the moment, we use it to store the lists of encoding that appears in
the encoding menu (to not have a too big encoding menu, user can choose which
encoding should be display, offering a small compact menu with all
its favorite encodings). We also cache encoding used to save or load a
file so that we can reuse it automatically next time the user want to
open the same file.

We also use this to cache some editor states (such as the last cursor position
for a specific file path)

We do not store editor styles and settings here. Those kind of settings are
better handled at the application level.

"""
import json
import locale
import logging
from pyqode.qt import QtCore

class Cache(object):
    """
    Provides an easy acces to the cache by exposing some wrapper properties
    over QSettings.

    """
    def __init__(self, suffix='', qsettings=None):
        if qsettings is None:
            self._settings = QtCore.QSettings('pyQode', 'pyqode.core%s' % suffix)
        else:
            self._settings = qsettings

    def clear(self):
        """
        Clears the cache.
        """
        self._settings.clear()

    @property
    def preferred_encodings(self):
        """
        The list of user defined encodings, for display in the encodings
        menu/combobox.

        """
        default_encodings = [
            locale.getpreferredencoding().lower().replace('-', '_')]
        if 'utf_8' not in default_encodings:
            default_encodings.append('utf_8')
        default_encodings = list(set(default_encodings))
        return json.loads(self._settings.value(
            'userDefinedEncodings', json.dumps(default_encodings)))

    @preferred_encodings.setter
    def preferred_encodings(self, value):
        from pyqode.core.api import encodings
        lst = [encodings.convert_to_codec_key(v) for v in value]
        self._settings.setValue('userDefinedEncodings',
                                json.dumps(list(set(lst))))

    def get_file_encoding(self, file_path, preferred_encoding=None):
        """
        Gets an eventual cached encoding for file_path.

        Raises a KeyError if no encoding were cached for the specified file
        path.

        :param file_path: path of the file to look up
        :returns: The cached encoding.
        """
        _logger().debug('getting encoding for %s', file_path)
        try:
            map = json.loads(self._settings.value('cachedFileEncodings'))
        except TypeError:
            map = {}
        try:
            return map[file_path]
        except KeyError:
            encodings = self.preferred_encodings
            if preferred_encoding:
                encodings.insert(0, preferred_encoding)
            for encoding in encodings:
                _logger().debug('trying encoding: %s', encoding)
                try:
                    with open(file_path, encoding=encoding) as f:
                        f.read()
                except (UnicodeDecodeError, IOError, OSError):
                    pass
                else:
                    return encoding
            raise KeyError(file_path)

    def set_file_encoding(self, path, encoding):
        """
        Cache encoding for the specified file path.

        :param path: path of the file to cache
        :param encoding: encoding to cache
        """
        try:
            map = json.loads(self._settings.value('cachedFileEncodings'))
        except TypeError:
            map = {}
        map[path] = encoding
        self._settings.setValue('cachedFileEncodings', json.dumps(map))

    def get_cursor_position(self, file_path):
        """
        Gets the cached cursor position for file_path

        :param file_path: path of the file in the cache
        :return: Cached cursor position or (0, 0)
        """
        try:
            map = json.loads(self._settings.value('cachedCursorPosition'))
        except TypeError:
            map = {}
        try:
            pos = map[file_path]
        except KeyError:
            pos = 0
        if isinstance(pos, list):
            # changed in pyqode 2.6.3, now we store the cursor position
            # instead of the line and column  (faster)
            pos = 0
        return pos

    def set_cursor_position(self, path, position):
        """
        Cache encoding for the specified file path.

        :param path: path of the file to cache
        :param position: cursor position to cache
        """
        try:
            map = json.loads(self._settings.value('cachedCursorPosition'))
        except TypeError:
            map = {}
        map[path] = position
        self._settings.setValue('cachedCursorPosition', json.dumps(map))


def _logger():
    return logging.getLogger(__name__)