pida-poelzi-main / pida / core / document.py

  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
# -*- coding: utf-8 -*- 
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
"""
    pida.core.document
    ~~~~~~~~~~~~~~~~~~

    :license: GPL2 or later
    :copyright: 2005-2008 by The PIDA Project

"""
import os
import mimetypes
import stat
import time

from charfinder import DETECTOR_MANAGER
import codecs

from pida.core.log import log
from pida.utils.descriptors import cached_property

from xml.sax.saxutils import escape

# locale
from pida.core.locale import Locale
locale = Locale('pida')
_ = locale.gettext

new_file_index = 1

class Document(object):
    """
    Represents a document.
    
    A document can eighter be just a file. Or be opened by the editor component
    and is then a live document (live is True).

    A document can be accessed like a List object (list of lines). Each line
    however does have its tailing newline character as it's supposed not
    to alter data.

    
    """

    markup_prefix = ''
    markup_directory_color = '#FFFF00'
    markup_project_color = '#FF0000'
    markup_attributes = ['project_name', 'project_relative_path', 'basename',
                         'markup_project_color', 'markup_directory_color', 
                         'filename', 'directory']

    markup_string_project = (
                     u'<span color="%(markup_project_color)s">'
                     u'%(project_name)s</span><tt>:</tt>'
                     u'<span color="%(markup_directory_color)s">'
                     u'%(project_relative_path)s/</span>'
                     u'<b>%(basename)s</b>')

    markup_string_fullpath = (
                     u'<span color="%(markup_directory_color)s">'
                     u'%(directory)s/</span>'
                     u'<b>%(basename)s</b>')
    
    markup_string_tworow = (
                     u'<b>%(basename)s</b>\n'
                     u'<small>%(markup_inc)s</small>')

    markup_string_tworow_project = (
                     u'<span foreground="%(markup_project_color)s">'
                     u'%(project_name)s</span><tt>:</tt>'
                     u'<span foreground="%(markup_directory_color)s">'
                     u'%(project_relative_path)s/</span>'
                     u'%(basename)s')

    markup_string_tworow_fullpath = (
                     u'<span foreground="%(markup_directory_color)s">'
                     u'%(directory)s/</span>'
                     u'%(basename)s')

    markup_string = (u'<b>%(basename)s</b>')


    def __init__(self, boss, filename=None, project=None):
        self.boss = boss
        self.filename = os.path.realpath(filename)
        self.project = project
        self.editor = None
        self._list = []
        self._str = ""
        self._detect_encoding = DETECTOR_MANAGER
        self.creation_time = time.time()

        if filename is None:
            global new_file_index
            self.newfile_index = new_file_index
            new_file_index = new_file_index + 1
        else:
            self.newfile_index = None

        if project is None:
            self.project, self.project_relative_path = self.get_project_relative_path()
        else:
            self.project_relative_path = project.get_relative_path_for(filename)

        self.clear()

    def clear(self):
        self._str = None
        self._lines = None
        self._encoding = None
        self._last_mtime = None

    def _load(self):
        """loads the document content/encoding

        sets the attributes _str, _lines and _encoding
        """

        if self.filename is None or self.modified_time == self._last_mtime:
            return


        # lines and string depend on encoding
        stream = None
        try:
            stream = open(self.filename, "rb")
            fname = self.filename
            mime = self.mimetype

            self._encoding = self._detect_encoding(stream, fname, mime)
            stream.seek(0)
            stream = codecs.EncodedFile(stream, self._encoding)
            self._str = stream.read()
            self._lines = self._str.splitlines(True)
        except IOError:
            if stream is not None:
                stream.close()

            # set the encoding to None and the rest too empty
            self.clear()
            self._str = ''
            self._lines = []
            self._encoding = 'none'

            log.warn(_('failed to open file %s'), self.filename)


    def _get_doctype(self):
        #FIXME: need a interface to pull doctype from the editor if 
        # we are live
        if hasattr(self, '_doctype'):
            return self._doctype
        elif self.boss:
            lmn = self.boss.get_service('language')
            if not lmn:
                return None
            self._doctype = lmn.doctypes.guess_doctype_for_document(self)

            return self._doctype

        return None

    def _set_doctype(self, doctype):
        #FIXME: we need a interface setting the editors language here
        self._doctype = doctype

    doctype = property(_get_doctype, _set_doctype)

    @property
    def stat(self):
        try:
            return os.stat(self.filename)
        except OSError:
            return (0,)*10

    @cached_property
    def mimetype(self):
        #FIXME: use doctypes
        typ, encoding = mimetypes.guess_type(self.filename)
        if typ is None:
            mimetype = ('', '')
        else:
            mimetype = tuple(typ.split('/'))
        return mimetype

    @property
    def filesize(self):
        return self.stat[stat.ST_SIZE]

    def __repr__(self):
        if self.filename is None:
            return u'<New Document %d (%s)>' %(self.newfile_index, self.unique_id)
        else:
            return u'<Document %r (%s)>' %(self.filename, self.unique_id)

    def __unicode__(self):
        if self.filename is None:
            if self.newfile_index > 1:
                return _(u'Untitled (%d)') %(self.newfile_index)
            return _(u'Untitled')
        else:
            if self.project:
                return u'%s:%s/%s' %(self.project_name,
                                     self.project_relative_path, self.basename)
            else:
                return os.path.basename(self.filename)

    @property
    def markup_title(self):
        """Returns a markup version of unicode"""
        if self.filename is None:
            if self.newfile_index > 1:
                return _(u'<b>Untitled (%d)</b>') %(self.newfile_index)
            return _(u'<b>Untitled</b>')
        else:
            if self.project:
                return u'%s:%s/<b>%s</b>' %(escape(self.project_name),
                                     escape(self.project_relative_path), 
                                     escape(self.basename))
            else:
                return '<b>%s</b>' %escape(os.path.basename(self.filename))

    @property
    def modified_time(self):
        return self.stat[stat.ST_MTIME]

    @property
    def encoding(self):
        self._load()
        # FIXME: if self.is_new we should run the _encode detection from
        # the editors buffer if possible
        return self._encoding

    @property
    def lines(self):
        import warnings
        warnings.warn("Deprecated. Access the document as a list")
        self._load()
        return self._lines

    @property
    def live(self):
        # live indicates that this object has a editor instance which get_content
        #self.live = False
        if self.editor and hasattr(self.editor, 'get_content'):
            return True

        return False

    def get_content(self):
        if hasattr(self.editor, 'get_content') and self.editor:
            return self.boss.editor.get_content(self.editor)
        self._load()
        return self._str

    def set_content(self, value, flush=True):
        if hasattr(self.boss.editor, 'set_content') and self.editor:
            return self.boss.editor.set_content(self.editor, value)

        self._str = value
        self._lines = self._str.splitlines(True)

        if flush:
            self.flush()

    content = property(get_content, set_content)

    def flush(self):
        if hasattr(self.editor, 'get_content') and self.editor:
            value = self.boss.editor.get_content(self.editor)
        else:
            value = self._str

        stream = None
        try:
            stream = open(self.filename, "wb")
            stream.write(value)
            stream.close()
            # update the _last_mtime var, so the next access
            # will not cause a file read
            self._last_mtime = self.modified_time
        except IOError:
            if stream is not None:
                stream.close()

    def _update_content_from_lines(self):
        self._str = "".join(self._lines)
        if hasattr(self.boss.editor, 'set_content') and self.editor:
            return self.boss.editor.set_content(self.editor, self._str)
        self.set_content(self._str, flush=False)

    @property
    def directory(self):
        if self.is_new:
            return None
        return os.path.dirname(self.filename)

    @property
    def directory_basename(self):
        if self.is_new:
            return None
        return os.path.basename(self.directory)

    @property
    def basename(self):
        if self.is_new:
            return None
        return os.path.basename(self.filename)

    @property
    def directory_colour(self):
        return self.markup_directory_color

    @property
    def unique_id(self):
        return id(self)

    def get_markup(self, markup_string=None, style=None):
        if markup_string is None:
            if self.project:
                markup_string = self.markup_string_project
            else:
                markup_string = self.markup_string

        prefix = u'<b><tt>%s </tt></b>' % self.markup_prefix
        if self.filename is not None:
            s = markup_string % self._build_markup_dict(style=style)
        else:
            s = u'<b>%s</b>' % escape(self.__unicode__())
        return '%s%s' % (prefix, s)

    markup = property(get_markup)

    def get_markup_tworow(self, style=None):
        if self.project:
            mark = self.get_markup(self.markup_string_tworow_project)
        else:
            mark = self.get_markup(self.markup_string_tworow_fullpath)
        rv = self.markup_string_tworow % self._build_markup_dict(markup_dict = {
            'markup_inc': mark
            }, style=style)
        return rv

    markup_tworow = property(get_markup_tworow)

    def _build_markup_dict(self, markup_dict=None, style=None):
        if not markup_dict:
            markup_dict = {}
        for attr in self.markup_attributes:
            var = getattr(self, attr)
            if var:
                markup_dict[attr] = escape(var)
            else:
                markup_dict[attr] = ''
        return markup_dict

    @property
    def project_name(self):
        if self.project is not None:
            return self.project.display_name
        else:
            return ''

    def get_project_relative_path(self):
        if self.filename is None:
            return None, None

        #XXX: move to buffer manager
        match = self.boss.cmd('project', 'get_project_for_document', document=self)
        if match is None:
            return None, os.path.join(*os.path.split(self.directory)[-2:])
        else:
            project, path = match
            return project, path


    @property
    def is_new(self):
        return self.filename is None

    # emulate a container element. this allows access to a document
    # as a list of lines
    def __len__(self):
        return len(self._list)

    def __getitem__(self, key):
        return self._list[key]

    def __setitem__(self, key, value):
        self._list[key] = value
        self._update_content_from_lines()

    def __delitem__(self, key):
        del self._list[key]
        self._update_content_from_lines()

    def __iter__(self):
        return iter(self._list)

    def append(self, line):
        self._list.append(line)
        self._update_content_from_lines()

    def __nonzero__(self):
        # documents are always True
        return True


class DocumentException(Exception):
    """Raised when the file can't be loaded by a editor"""
    def __init__(self, *args, **kwargs):
        self.document = kwargs.pop('document', None)
        self.orig = kwargs.pop('orig', None)
        super(DocumentException, self).__init__(*args, **kwargs)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.