Source

pida-hacks / pida-plugins / bookmark / bookmark.py

Full commit
  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
# -*- coding: utf-8 -*- 

import gtk
import os
import cgi
import pkgutil
import json

from pygtkhelpers.ui.objectlist import ObjectList, Column

# PIDA Imports
from pida.core.service import Service
from pida.core.features import FeaturesConfig
from pida.core.events import EventsConfig
from pida.core.actions import ActionsConfig
from pida.ui.actions import PidaRememberToggle
from pida.core.editors import LineMarker, MarkerInterface

from pida.ui.views import PidaView

from pygtkhelpers.gthreads import gcall
from pygtkhelpers.utils import eformat

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

class BookmarkItem(object):
    group = None

    def __init__(self, title, data, line=None):
        self.title = title
        self.data = data
        self.line = line

    def run(self, service):
        pass

    def _key(self):
        return self.data, self.group, self.title, self.line

    def __eq__(self, other):
        return self._key() == other._key()


class BookmarkItemFile(BookmarkItem, LineMarker):
    group = 'file'
    type = 'bookmark'

    def __init__(self, svc, data=None, line=1):
        #self.line = line
        self.svc = svc
        self._lineno = line
        BookmarkItem.__init__(self,  title='', data=data, line=line)
        self.data = data

    @property
    def title(self):
        try:
            color = self.svc._view._list['file'].style.lookup_color('pida-lineno').\
                    to_string()
        except:
            color = "black"
        try:
            line = int(self.line)
        except ValueError:
            line = 1
        return eformat('{name:e}:<span color="{color}">{line}</span>',
                           name=os.path.basename(self.filename),
                           color=color,
                           line=line,
            )

    @title.setter
    def title(self, value):
        pass  # ignore

    def run(self, service):
        service.boss.cmd('buffer', 'open_file', 
                         file_name=self.data, line=self.line)

    def _get_filename(self):
        return self.data

    def _set_filename(self, value):
        self.data = value

    filename = property(_get_filename, _set_filename)

    def _do_set_line(self, newlineno):
        self._lineno = int(newlineno)
        self.svc._view._list['file'].update(self)

    def update(self, newlineno):
        gcall(self._do_set_line, newlineno)

class BookmarkItemPath(BookmarkItem):
    group = 'path'
    ICON_NAME = 'folder'

    def __init__(self, title='no title', data=None):
        BookmarkItem.__init__(self,  title=title, data=data)

    def run(self, service):
        service.boss.cmd('filemanager', 'browse', new_path=self.data)
        service.boss.cmd('filemanager', 'present_view')

"""
class BookmarkItemUrl(BookmarkItem):
    group = 'url'
    ICON_NAME = 'www'

    def __init__(self, title='no title', data=None):
        BookmarkItem.__init__(self, title=title, data=data)

    def run(self, service):
        service.boss.call_command('browseweb', 'browse', url=self.data)
"""


class BookmarkView(PidaView):

    key = 'bookmark.view'

    icon_name = 'gtk-library'
    label_text = _('Bookmarks')

    def create_ui(self):
        self.create_toolbar()
        self.create_ui_list()

    def create_tab_label(self, icon_name, text):
        label = gtk.Label(text)
        icon = gtk.image_new_from_stock(icon_name, gtk.ICON_SIZE_MENU)
        box = gtk.HBox(spacing=2)
        box.pack_start(icon)
        box.pack_start(label)
        box.show_all()
        return box

    def create_objectlist(self, icon_name, text):
        l = ObjectList([Column('title', use_markup=True)])
        l.connect('item-activated', self._on_item_activated)
        l.connect('selection-changed', self._on_item_selected)
        l.set_headers_visible(False)
        sc = gtk.ScrolledWindow()
        sc.add(l)
        sc.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self._books.append_page(sc,
                tab_label=self.create_tab_label(icon_name, text))
        return l

    def create_ui_list(self):
        self._books = gtk.Notebook()
        self._books.set_border_width(6)
        self._list = {}
        self._list['file'] = self.create_objectlist('text-x-generic', _('Files'))
        self._list['path'] = self.create_objectlist('stock_folder', _('Dirs'))
        """
        self._list_url = ObjectList([Column('markup', data_type=str, use_markup=True)])
        self._list_url.set_headers_visible(False)
        self._books.add(self._list_url)
        """
        self.widget.add(self._books)
        self._books.show_all()

    def create_toolbar(self):
        self._uim = gtk.UIManager()
        self._uim.insert_action_group(self.svc.get_action_group(), 0)
        uidef_data = pkgutil.get_data(__name__, 'uidef/bookmark-toolbar.xml')
        self._uim.add_ui_from_string(uidef_data)
        self._uim.ensure_update()
        self._toolbar = self._uim.get_toplevels('toolbar')[0]
        self._toolbar.set_style(gtk.TOOLBAR_ICONS)
        self._toolbar.set_icon_size(gtk.ICON_SIZE_SMALL_TOOLBAR)
        self.widget.pack_start(self._toolbar, expand=False)
        self._toolbar.show_all()

    def add_item(self, item):
        self._list[item.group].append(item)

    def remove_item(self, item):
        self._list[item.group].remove(item)

    def clear_all(self):
        for l in self._list.values():
            l.clear()

    def can_be_closed(self):
        self.svc.get_action('show_bookmark').set_active(False)

    def _on_item_selected(self, olist):
        self.svc.set_current(olist.selected_item)

    def _on_item_activated(self, olist, item):
        item.run(self.svc)

class BookmarkActions(ActionsConfig):


    actions = [
        PidaRememberToggle('show_bookmark',
            _('Bookmark Viewer'),
            _('Show bookmarks'),
            ''),
        gtk.Action('bookmark_curfile',
            _('Bookmark current file'),
            _('Bookmark current file'),
            'text-x-generic'),
        gtk.Action('bookmark_togglefile',
            _('Toggle Bookmark on current file'),
            _('Toggle Bookmark on current file'),
            'text-x-generic'),
        gtk.Action('bookmark_curdir',
            _('Bookmark current directory'),
            _('Bookmark current directory'),
            'stock_folder'),
        gtk.Action('bookmark_delsel',
            _('Delete selected item'),
            _('Delete selected item'),
            gtk.STOCK_DELETE),
        gtk.Action('bookmark_go_prev',
            _('Goto previous bookmark'),
            _('Goto previous bookmark'),
            gtk.STOCK_GO_UP),
        gtk.Action('bookmark_go_next',
            _('Goto next bookmark'),
            _('Goto next bookmark'),
            gtk.STOCK_GO_DOWN),
        gtk.Action('bookmark_for_dir',
            _('Add as bookmark'),
            _('Add selected directory as bookmark'),
            gtk.STOCK_ADD),
        gtk.Action('bookmark_for_file',
            _('Add as bookmark'),
            _('Add selected file as bookmark'),
            gtk.STOCK_ADD),
    ]

    accels = {
        'show_bookmark': '',
        'bookmark_curfile': '',
        'bookmark_togglefile': '',
        'bookmark_curdir': '',
        'bookmark_delsel': '',
        'bookmark_go_prev': '',
        'bookmark_go_next': '',
    }

    def on_show_bookmark(self, action):
        if action.get_active():
            self.svc.show_bookmark()
        else:
            self.svc.hide_bookmark()

    def on_bookmark_curdir(self, action):
        self.svc.bookmark_dir()

    def on_bookmark_curfile(self, action):
        self.svc.bookmark_file()

    def on_bookmark_togglefile(self, action):
        self.svc.bookmark_toggle_file()

    def on_bookmark_delsel(self, action):
        self.svc.remove_current()

    def on_bookmark_go_next(self, action):
        self.svc.goto_next()

    def on_bookmark_go_prev(self, action):
        self.svc.goto_prev()

    def on_bookmark_for_file(self, action):
        self.svc.bookmark_file(filename=action.contexts_kw['file_name'])

    def on_bookmark_for_dir(self, action):
        self.svc.bookmark_dir(path=action.contexts_kw['dir_name'])

class BookmarkFeatures(FeaturesConfig):

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

class BookmarkEvents(EventsConfig):

    def subscribe_all_foreign(self):
        self.subscribe_foreign('project', 'project_switched',
                               self.svc.on_project_switched)
        self.subscribe_foreign('buffer', 'document-opened',
                               self.svc.update_document)
        self.subscribe_foreign('buffer', 'document-saved',
                               self.on_document_saved)

    def on_document_saved(self, document=None):
        # we have to save, because we can't detect removed bookmarks yet
        return self.svc.save()


# Service class
class Bookmark(Service, MarkerInterface):
    """Manage bookmarks"""

    actions_config = BookmarkActions
    features_config = BookmarkFeatures
    events_config = BookmarkEvents

    def start(self):
        self._view = BookmarkView(self)
        self._has_loaded = False
        self._items = []
        self._current = None
        self._project = None
        self.load()

    def show_bookmark(self):
        self.boss.cmd('window', 'add_view', paned='Plugin', view=self._view)
        if not self._has_loaded:
            self._has_loaded = True

    def hide_bookmark(self):
        self.boss.cmd('window', 'remove_view', view=self._view)


    def set_current(self, item):
        self._current = item

    def add_item(self, item):
        for t in self._items:
            if t == item:
                return
        self._items.append(item)
        self._view.add_item(item)
        self.save()

    def list_files(self):
        return self._view._list['file']

    def list_dirs(self):
        return self._view._list['path']

    def remove_current(self):
        if self._current == None:
            return
        self._items.remove(self._current)
        self._view.remove_item(self._current)
        self._current = None
        self.save()

    def bookmark_dir(self, path=None):
        if path == None:
            path = self.boss.cmd('filemanager', 'get_browsed_path')
        source_directory = self.boss.cmd('project', 'get_current_project').source_directory
        title = path
        if title.startswith(source_directory):
            title = title[len(source_directory):]
            if title == '':
                title = _('(project root)')
            else:
                title = '.' + title
        item = BookmarkItemPath(title=title, data=path)
        self.add_item(item)

    def _fill_file(self, filename, line):
        if filename == None:
            document = self.boss.cmd('buffer', 'get_current')
            if document == None:
                return
            filename = document.filename
        if line == None:
            line = self.boss.editor.cmd('get_current_line_number')
        return (filename, line)

    def bookmark_file(self, filename=None, line=None):
        filename, line = self._fill_file(filename, line)
        item = BookmarkItemFile(self, data=filename, line=line)
        self.add_item(item)
        self.boss.get_service('editor').emit('marker-changed', marker=item)

    def bookmark_toggle_file(self, filename=None, line=None):
        """
        Add/removed a bookmark depending if there is already one
        """
        filename, line = self._fill_file(filename, line)
        for item in self.list_files():
            if item.data == filename and item.line == line:
                # change the line to -1 and fire the marker-changed so it's 
                # known that the marker will be removed
                item._lineno = -1
                self.boss.get_service('editor'). \
                    emit('marker-changed', marker=item)
                self._items.remove(item)
                self._view.remove_item(item)
                if self._current == item:
                    self._current = None
                break
        else:
            self.bookmark_file(filename, line)

    def update_document(self, document):
        for item in self.list_files():
            if document.filename == item.data:
                self.boss.get_service('editor'). \
                    emit('marker-changed', marker=item)

    def on_project_switched(self, project):
        if project != self._project:
            self._project = project
            self.load()

    def _serialize(self):
        data = {}
        for t in self._items:
            if not data.has_key(t.group):
                data[t.group] = []
            if t.group == 'file':
                if self._project:
                    path = self._project.get_relative_path_for(t.data)
                else:
                    path = None
                if path:
                    path = os.path.sep.join(path)
                else:
                    path = t.data
                data[t.group].append('%s#%d' %( path, int(t.line)))
            else:
                data[t.group].append(t.data)
        return data

    def _unserialize(self, data):
        if data == None:
            return
        for key in data:
            items = data[key]
            for item in items:
                if key == 'file':
                    try:
                        item = item.rsplit('#', 1)
                    except AttributeError:
                        pass  # old format
                    path = os.path.join(self._project.source_directory,  item[0])
                    self.bookmark_file(filename=path, line=int(item[1]))
                elif key == 'path':
                    self.bookmark_dir(path=item)

    def load(self):
        self._items = []
        self._view.clear_all()
        pro = self.boss.cmd('project', 'get_current_project')
        if not pro:
            return
        self._project = pro
        datadir = pro.get_meta_dir('bookmark')
        datafile = os.path.join(datadir, 'bookmark.json')
        if os.path.isfile(datafile):
            try:
                fp = open(datafile, "r")
                data = json.load(fp)
                self._unserialize(data)
            except Exception, e:
                self.log.exception(e)
                return
            
        #self._unserialize(data)

    def save(self):
        data = self._serialize()
        pro = self.boss.cmd('project', 'get_current_project')
        if not pro:
            #FIXME: should we save it in the default settings ?
            return
        else:
            datadir = pro.get_meta_dir('bookmark')
            datafile = os.path.join(datadir, 'bookmark.json')
        try:
            fp = open(datafile, "w")
            json.dump(data, fp, indent=1)
        except Exception, e:
            print e
            self.log.exception(e)
            
        #FIXME: reimplement !!!
        #self.boss.cmd('project', 'save_to_current_project',
        #        section_name='bookmark', section_data=data)

    def stop(self):
        if self.get_action('show_bookmark').get_active():
            self.hide_bookmark()

    def _goto(self, direction):
        if not self._view:
            return
        lst = self._view._list['file']
        if not len(lst):
            return
        cur = lst.get_selected()
        if not cur:
            cur = lst.select_paths([0])
            cur = lst.get_selected()
        if direction > 0:
            sel = lst.get_next(cur)
        else:
            sel = lst.get_previous(cur)
        lst.select(sel)
        self.set_current(sel)
        sel.run(self)

    def goto_next(self):
        self._goto(1)
    
    def goto_prev(self):
        self._goto(-1)
        
    def get_line_markers(self, filename):
        for i in self._list['file']:
            if i.data == filename:
                yield i

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