Source

pida-hacks / pida / services / buffer / buffer.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
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
# -*- coding: utf-8 -*-
"""
    :copyright: 2005-2008 by The PIDA Project
    :license: GPL 2 or later (see README/COPYING/LICENSE)
"""
import os

import gtk
import time


# PIDA Imports
from pida.core.service import Service
from pida.core.features import FeaturesConfig
from pida.core.commands import CommandsConfig
from pida.core.options import OptionsConfig, choices
from pida.core.events import EventsConfig
from pida.core.actions import ActionsConfig

from pida.core.document import Document, DocumentException

from pygtkhelpers.gthreads import gcall

from . import _
from .view import BufferListView, attributes, markup_extras


class BufferActionsConfig(ActionsConfig):
    accels = {
        'open_file': '<Shift><Control>O',
        'new_file': '<Shift><Control>N',
        'create_file': '<Shift><Control>A',
        'close': '<Shift><Control>W',
        'close_all': '',
        'switch_prev_buffer': '<Alt>Up',
        'switch_next_buffer': '<Alt>Down',
    }

    global_accels = {
        'show_buffer_list': '<Shift><Control>b',
    }

    actions = [
        gtk.Action('open_file',
            _('_Open File'),
            _('Open a file with a graphical file browser'),
            gtk.STOCK_OPEN),

        gtk.Action('open_for_file',
            _('Open File'),
            _('Open this file'),
            gtk.STOCK_OPEN),

        gtk.Action('new_file',
            _('_New File'),
            _('Create a new file'),
            gtk.STOCK_NEW),

        gtk.Action('create_file',
            _('Cr_eate File'),
            _('Create a new file'),
            gtk.STOCK_ADD),

        gtk.Action('close',
            _('_Close Document'),
            _('Close the current document'),
            gtk.STOCK_CLOSE),

        gtk.Action('close_all',
            _('Close all Documents'),
            _('Close all documents'),
            ''),

        gtk.Action('switch_next_buffer',
            _('_Next Buffer'),
            _('Switch to the next buffer'),
            gtk.STOCK_GO_DOWN),

        gtk.Action('switch_prev_buffer',
            _('_Previous Buffer'),
            _('Switch to the previous buffer'),
            gtk.STOCK_GO_UP),

        gtk.Action('show_buffer_list',
            _('Show _buffer browser'),
            _('Displays the buffer window'),
            ''),

        gtk.Action('close_selected',
            _('_Close Document'),
            _('Close the selected document'),
            gtk.STOCK_CLOSE),
    ]

    def on_open_file(self, action):
        project = self.svc.boss.cmd('project', 'get_current_project')
        if project:
            current_folder = project.source_directory
        else:
            current_folder = None 
        file_name = self.svc.boss.window.open_dlg(folder=current_folder)
        if file_name:
            self.svc.open_file(file_name)

    def on_new_file(self, action):
        self.svc.new_file()

    def on_create_file(self, action):
        current_folder = self.svc.boss.cmd('filemanager', 'get_browsed_path')
        file_name = self.svc.boss.window.save_dlg(folder=current_folder)
        if file_name:
            f = open(file_name, 'w')
            f.close()
            self.svc.open_file(file_name)

    def on_close(self, action):
        self.svc.close_current()

    def on_close_all(self, action):
        self.svc.close_all()

    def on_open_for_file(self, action):
        file_name = action.contexts_kw['file_name']
        self.svc.open_file(file_name)

    def on_switch_next_buffer(self, action):
        self.svc.get_view().next_buffer()

    def on_switch_prev_buffer(self, action):
        self.svc.get_view().prev_buffer()

    def on_show_buffer_list(self, action):
        self.svc.cmd('present_view')

    def on_close_selected(self, action):
        document = action.contexts_kw.get('document')
        self.svc.close_file(document=document)

class BufferFeaturesConfig(FeaturesConfig):

    def subscribe_all_foreign(self):
        self.subscribe_foreign('contexts', 'file-menu',
            (self.svc, 'buffer-file-menu.xml'))

class BufferEventsConfig(EventsConfig):

    def create(self):
        self.publish('document-saved', 'document-changed', 
            'document-typchanged', 'document-closed', 'document-opened', 
            'document-goto')
        self.subscribe('document-saved', self.on_document_change)
        self.subscribe('document-changed', self.on_document_change)
        self.subscribe('document-typchanged', self.on_document_change)

    def subscribe_all_foreign(self):
        self.subscribe_foreign('editor', 'started', self.on_editor_started)
        self.subscribe_foreign('optionsmanager', 'option_changed', self.on_options_changed)

    def on_editor_started(self, *k, **kw):

        try:
            #XXX: will mess wuth the signaling doe opening files
            #     will create inconsistent state while the default impl is
            #     working
            files = self.svc.opt('open_files')
            self.svc.log.info( 'opening {files}', files=files)
            self.svc.open_files(files)
        except Exception as e:
            self.svc.log.exception(e)

        # we can now, as the saved file list is open, register to the
        # change list events to have an up to date list
        self.subscribe('document-opened', self.on_document_list_change)
        self.subscribe('document-closed', self.on_document_list_change)


    def on_document_list_change(self, *args, **kwargs):
        self.svc.save_filelist()

    def on_document_change(self, *args, **kwargs):
        # we have to update the document buffer when one doc changes as
        # the list should be sorted all the time
        self.svc.get_view().sort()

    def on_options_changed(self, *args, **kwargs):
        self.svc.update_colors()

class BufferOptionsConfig(OptionsConfig):
    def create_options(self):
        self.create_option(
            'display_type',
            _('Display notebook title'),
            choices({'onerow':_('One Row'), 
                     'tworow':_('Filename and Path seperate ')}),
            'tworow',
            _('Type to display in the Buffer window'),
            self.on_display_type_change
        )
        self.create_option(
            'open_files',
            'the currently open files',
            list,
            [],
            '',
            workspace=True,
        )

    def on_display_type_change(self, option):
        self.svc.get_view().set_display_attr(attributes[option.value])


class BufferCommandsConfig(CommandsConfig):

    def new_file(self, do_open=True, with_editor_id=None):
        self.svc.new_file(do_open, with_editor_id)

    def open_file(self, file_name=None, document=None, line=None, offset=None,
                  editor_buffer_id=None, do_open=True):
        #if not file_name and not document and not editor_buffer_id:
        #    return
        self.svc.open_file(file_name, document, line=line, offset=offset,
                           editor_buffer_id=editor_buffer_id, do_open=do_open)

    def open_files(self, files):
        self.svc.open_files(files)

    def close_file(self, file_name=None, document=None,
                   editor_buffer_id=None):
        #if not file_name and not document:
        #    return
        self.svc.close_file(file_name=file_name, document=document,
                            editor_buffer_id=editor_buffer_id)

    def close_all(self):
        self.svc.close_all()

    def current_file_saved(self):
        self.svc.file_saved()

    def get_view(self):
        return self.svc.get_view()

    def get_current(self):
        return self.svc.get_current()

    def get_documents(self):
        return self.svc.get_documents()

    def get_buffer_names(self):
        return [x.filename for x in self.get_documents().itervalues()]

    def present_view(self):
        view = self.svc.get_view()
        return self.svc.boss.cmd('window', 'present_view',
            view=view)
        view.buffers_ol.grab_focus()

    def get_document_by_id(self, document_id=None):
        if document_id:
            return self.svc._documents.get(document_id, None)

# Service class
class Buffer(Service):
    """
    Buffer is a graphical manager for editor buffers.
    """ 

    commands_config = BufferCommandsConfig
    actions_config = BufferActionsConfig
    events_config = BufferEventsConfig
    features_config = BufferFeaturesConfig
    options_config = BufferOptionsConfig

    def pre_start(self):
        self._documents = {}
        self._current = None
        #XXX hideous hack for vim
        self._last_added_document = None
        self._view = BufferListView(self)
        self._view.set_display_attr(attributes[self.opt('display_type')])
        self.get_action('close').set_sensitive(False)
        self._refresh_buffer_action_sensitivities()
        self.update_colors()

    def save_filelist(self):
        self.set_opt('open_files', [
            d.filename for d in self._documents.itervalues()
            if d.filename is not None
            ])

    def pre_stop(self):
        self.save_filelist()
        return True

    def get_view(self):
        return self._view

    def _refresh_buffer_action_sensitivities(self):
        for action_name in ['switch_next_buffer', 'switch_prev_buffer']:
            self.get_action(action_name).set_sensitive(bool(self._documents))

    def new_file(self, do_open=True, with_editor_id=None):
        return self.open_file(editor_buffer_id=with_editor_id)

    def open_file(self, file_name=None, document=None, line=None, offset=None,
                  editor_buffer_id=None, do_open=True):
        if file_name:
            file_name = os.path.realpath(file_name)
        if document is None:
            # try to find the document
            if editor_buffer_id is not None:
                document = self._get_document_for_editor_id(editor_buffer_id)
            if document is None and file_name is not None:
                document = self._get_document_for_filename(file_name)
            elif file_name is None and editor_buffer_id is not None:
                #XXX new file just switched, can't know, have to guess!
                # normally fall back to filename
                if self._last_added_document and self._last_added_document.is_new:
                    document = self._last_added_document
                    self._last_added_document = None
            # can't find it
            if document is None:
                document = Document(self.boss, file_name)
                if editor_buffer_id is not None:
                    document.editor_buffer_id = editor_buffer_id
                self._add_document(document)
        self.view_document(document, line=line, offset=offset, do_open=do_open)
        self.emit('document-opened', document=document)
        return document


    def open_files(self, files):
        if not files:
            # empty list
            return
        docs = []
        for file_name in files:
            document = Document(self.boss, file_name)
            self._add_document(document)
            docs.append(document)
        self.boss.editor.cmd('open_list', documents=docs)
        for document in docs:
            self.emit('document-opened', document=document)

    def recover_loading_error(self, error):
        # recover from a loading exception
        if error.document:
            filename = error.document.filename
        else:
            filename = ""
        self.notify_user(error.message, title=_("Can't load file %s") % filename )
        self.log.warning('error loading file(s): {files}',
                         files=error.message)
        if error.document:
            self._remove_document(error.document)
        # switch to the first doc to make sure editor gets consistent
        if self._documents:
            self.view_document(self._documents[self._documents.keys()[0]])
        #self.log.exception(err)

    def close_current(self):
        document = self._current
        if document is not None:
            if self.boss.editor.cmd('close', document=document):
                self._remove_document(document)
                self.emit('document-closed', document=document)

    def close_file(self, file_name = None, document = None,
                   editor_buffer_id=None):

        if not document:
            if editor_buffer_id is not None:
                document = self._get_document_for_editor_id(editor_buffer_id)
            if not document and file_name is not None:
                document = self._get_document_for_filename(file_name)
        if document is not None:
            if editor_buffer_id is not None:
                self._remove_document(document)
                self.emit('document-closed', document=document)
            else:
                if self.boss.editor.cmd('close', document=document):
                    self._remove_document(document)
                    self.emit('document-closed', document=document)

    def close_all(self):
        docs = self._documents.values()[:]
        for document in docs:
            if self.boss.editor.cmd('close', document=document):
                self._remove_document(document)
                self.emit('document-closed', document=document)
            else:
                break

    def _get_document_for_filename(self, file_name):
        for uid, doc in self._documents.iteritems():
            if doc.filename == file_name:
                return doc

    def _get_document_for_editor_id(self, bufid):
        for uid, doc in self._documents.iteritems():
            if doc.editor_buffer_id == bufid:
                return doc


    def _add_document(self, document):
        self._last_added_document = document
        self._documents[id(document)] = document
        self._view.add_document(document)
        self._refresh_buffer_action_sensitivities()

    def _remove_document(self, document):
        "_remove_doc", document
        del self._documents[id(document)]
        self._view.remove_document(document)
        self._refresh_buffer_action_sensitivities()

    def view_document(self, document, line=None, offset=None, do_open=True):
        self._view.buffers_ol.update(document)
        if document is not None and self._current != document:
            self._current = document
            self._current.usage += 1
            self._current.last_opend = time.time()
            self._view.set_document(document)
            try:
                if do_open:
                    self.boss.editor.cmd('open', document=document)
            except DocumentException, e:
                # document can't be loaded. we have to remove the document from 
                # the system
                self.recover_loading_error(e)
                return
            self.emit('document-changed', document=document)
        if offset is not None:
            if line is not None:
                raise ValueError('Cannot pass offset and line')
            else:
                gcall(self.boss.editor.set_cursor_position, offset)
        elif line is not None:
            gcall(self.boss.editor.goto_line, line)
        self.get_action('close').set_sensitive(document is not None)

    def file_saved(self):
        self.emit('document-saved', document=self._current)

    def get_current(self):
        return self._current

    def get_documents(self):
        return self._documents

    def update_colors(self):
        woptions = self.boss.get_service('window').options
        markup_extras['directory_color'] = str(woptions.get_value('directory_color'))
        markup_extras['project_color'] = str(woptions.get_value('project_color'))
        markup_extras['no_project_color'] = str(woptions.get_value('no_project_color'))

# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: