Source

qtgrin / qtgrin / qtgrin.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
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

from collections import defaultdict
import csv
import gzip
import os
import re
import shlex
import subprocess
import threading

from PyQt4 import QtGui
from PyQt4.QtCore import Qt

from enthought.etsconfig.api import ETSConfig
ETSConfig.toolkit = 'qt4'
ETSConfig.company = 'qtgrin'

from enthought.pyface.image_resource import ImageResource
from enthought.traits import api as traits
from enthought.traits.ui import api as ui
from enthought.traits.ui import menu
from enthought.traits.ui.key_bindings import KeyBinding, KeyBindings
from enthought.traits.ui.qt4.extra.qt_view import QtView
from enthought.traits.ui.tabular_adapter import TabularAdapter

import grin


style_sheet = """
QTableView {
    font-family: "Courier New";
    font-size: 10pt;
}
"""

class SelectBookmarkAction(menu.Action):
    """ Select a bookmark.
    """

    # The QtGrin instance.
    app = traits.WeakRef()


    def perform(self, event=None):
        if self.app is not None:
            roots = None
            for name, dirs in self.app.bookmarks:
                if name == self.name:
                    roots = dirs
                    break
            if roots is not None:
                self.app.current_root = ''
                self.app.other_roots = roots


class Searcher(traits.HasTraits):
    """ Model for performing a single search.
    """

    #### Configuration traits #################################################

    # The root directories to search.
    roots = traits.List(traits.Str)

    # The search regex.
    regex = traits.Str()

    # Whether or not we should ignore case.
    ignore_case = traits.Bool(False)


    #### State traits ##########################################################

    # The grepper object.
    grepper = traits.Property(traits.Instance(grin.GrepText),
        depends_on=['regex', 'ignore_case'])
    def _get_grepper(self):
        flags = 0
        if self.ignore_case:
            flags |= re.I
        regex = re.compile(self.regex, flags)
        grepper = grin.GrepText(regex)
        return grepper

    # The results of the search.
    results = traits.List(traits.Tuple(traits.Str, traits.Int,
        traits.Enum(grin.PRE, grin.MATCH, grin.POST), traits.Str, traits.List))


    def search(self):
        """ Perform the search and place the results incrementally into the
        results list.

        We don't return the results directly because this function will
        typically be run in a thread and communicated back to the main GUI
        thread through event notifications.
        """
        self.results = []
        p = grin.get_grin_arg_parser()
        args = p.parse_args(['fake_regex'] + self.roots)
        openers = dict(text=open, gzip=gzip.open)
        for filename, kind in grin.get_filenames(args):
            opener = openers[kind]
            with opener(filename, 'r') as f:
                unique_context = self.grepper.do_grep(f)
            self.results.extend([(filename,) + tup for tup in unique_context])


class GetAName(traits.HasTraits):
    """ Simple dialog for getting a name from the user.
    """

    # The requested value.
    name = traits.Str()

    # The title text.
    title = traits.Str()

    def default_traits_view(self):
        traits_view = ui.View(
            ui.Item('name'),
            title=self.title,
            buttons=['OK', 'Cancel'],
            width=300,
            height=200,
        )
        return traits_view


class ResultsAdapter(TabularAdapter):
    columns = [
        ('File', 'filename'),
        ('#', 'lineno'),
        ('Line', 'linetext'),
    ]

    filename_width = traits.Int(400)
    lineno_width = traits.Int(50)
    linetext_width = traits.Int(1000)
    filename_text = traits.Property()
    lineno_text = traits.Property()
    linetext_text = traits.Property()
    lineno_alignment = traits.Str('right')

    def _get_filename_text(self):
        return self.item[0]

    def _get_lineno_text(self):
        return str(self.item[1]+1)

    def _get_linetext_text(self):
        return self.item[3]


class QtGrin(ui.Controller):
    """ A simple GUI interface for grin.
    """

    # The current root directory to search.
    current_root = traits.Str()

    # The other directories to search.
    other_roots = traits.List(traits.Str)

    # Browse directories.
    browse_dir = traits.ToolbarButton(u'\u2026')

    # Add a directory to the list of roots.
    add_root = traits.ToolbarButton('+')

    # Bookmark the current set of roots.
    bookmark = traits.ToolbarButton(image=ImageResource('bookmark_add'))

    # The bookmarks.
    # (name, [dir1, dir2, ...])
    bookmarks = traits.List(traits.Tuple(traits.Str, traits.List(traits.Str)))

    # Trigger the search.
    search = traits.Button('Search', style='toolbar')

    # The double-clicked row in the results table.
    results_dclick = traits.Event()

    # The command line template for editing a file.
    command_template = traits.Str('gvim +{lineno} "{filename}"')

    # All of the root directories.
    all_roots = traits.Property(traits.List(traits.Str),
        depends_on=['current_root', 'other_roots', 'other_roots_items'])

    # The menu group with dynamic bookmarks.
    bookmark_menu_group = traits.Instance(menu.ActionGroup,
        kw=dict(id='bookmarks'))

    # The bookmark file.
    bookmark_file = traits.Str()
    def _bookmark_file_default(self):
        config_dir = ETSConfig.get_application_data(create=True)
        bookmark_file = os.path.join(config_dir, 'bookmarks.csv')
        return bookmark_file

    # The bookmark menu.
    bookmark_menu = traits.Instance(menu.Menu)
    def _bookmark_menu_default(self):
        return menu.Menu(
            self.bookmark_menu_group,
            name=u'Bookmarks',
        )

    # Whether we are currently searching or not.
    searching = traits.Bool(False)

    # The worker thread.
    worker = traits.Any()
    def _worker_default(self):
        worker = threading.Thread(target=self._thread_main)
        worker.daemon = True
        return worker

    # Notify the worker thread that there is a new query to search.
    new_query = traits.Any()
    def _new_query_default(self):
        return threading.Event()


    def default_traits_view(self):
        traits_view = QtView(
            ui.VGroup(
                ui.HGroup(
                    ui.VGroup(
                        ui.HGroup(
                            ui.UCustom('controller.search', enabled_when='object.regex.strip()'),
                            ui.UItem('regex',
                                editor=ui.TextEditor(auto_set=True),
                                springy=True, has_focus=True),
                        ),
                        ui.Item('ignore_case'),
                        label="Regex",
                        enabled_when='not controller.searching',
                        show_border=True,
                    ),
                    ui.VGroup(
                        ui.HGroup(
                            ui.UItem('controller.current_root', springy=True),
                            ui.UCustom('controller.browse_dir'),
                            ui.UCustom('controller.add_root',
                                enabled_when="controller.current_root.strip()"),
                            ui.UCustom('controller.bookmark',
                                enabled_when="controller.all_roots"),
                        ),
                        ui.VGroup(
                            ui.UItem('controller.other_roots',
                                editor=ui.ListStrEditor(
                                    title='Roots',
                                    operations=['delete'],
                                ),
                                height=-60,
                            ),
                        ),
                        label="Directories",
                        show_border=True,
                        enabled_when='not controller.searching',
                    ),
                    springy=False,
                ),
                ui.VGroup(
                    ui.UItem('results',
                        editor=ui.TabularEditor(
                            adapter=ResultsAdapter(),
                            dclicked='controller.results_dclick',
                            operations=[],
                            editable=False,
                        ),
                        height=600,
                        springy=True,
                    ),
                    springy=True,
                ),
            ),
            key_bindings=KeyBindings(
                KeyBinding(
                    binding1='Enter',
                    description='Search',
                    method_name='do_search',
                ),
                KeyBinding(
                    binding1='Cmd-D',
                    description='Bookmark',
                    method_name='do_bookmark',
                ),
            ),
            style_sheet=style_sheet,
            menubar=menu.MenuBar(
                self.bookmark_menu,
            ),
            title="Grin",
            width=800,
            height=600,
            id='QtGrin_View',
            resizable=True,
        )
        return traits_view

    def init(self, info):
        """ Initialize the controls of a user interface.
        """
        self.worker.start()
        table_views = info.ui.control.findChildren(QtGui.QTableView)
        for tv in table_views:
            tv.setAlternatingRowColors(True)
            tv.setTextElideMode(Qt.ElideLeft)
        self.load_bookmark_csv()
        return True

    def closed(self, info, is_ok):
        """ Handles a dialog-based user interface being closed by the user.
        """
        self.save_bookmark_csv()

    def save_bookmark_csv(self, filename=None):
        """ Save the bookmarks.
        """
        if filename is None:
            filename = self.bookmark_file
        with open(filename, 'w') as f:
            w = csv.writer(f)
            for name, roots in self.bookmarks:
                for dir in roots:
                    w.writerow([name, os.path.abspath(dir)])

    def load_bookmark_csv(self, filename=None):
        """ Load the bookmarks from CSV.
        """
        if filename is None:
            filename = self.bookmark_file
        if not os.path.isfile(filename):
            return
        bookmark_map = defaultdict(list)
        name_order = []
        try:
            with open(filename, 'r') as f:
                for row in csv.reader(f):
                    row = [x.strip() for x in row if x.strip()]
                    if len(row) != 2:
                        continue
                    name, root = row
                    bookmark_map[name].append(root)
                    if name not in name_order:
                        name_order.append(name)
        except csv.Error:
            # FIXME: raise a dialog?
            return

        bookmarks = []
        for name in name_order:
            bookmarks.append((name, bookmark_map[name]))
        self.bookmarks = bookmarks

    def do_search(self, info):
        """ Perform the search.
        """
        self._search_changed()

    def do_bookmark(self, info):
        """ Bookmark the directories.
        """
        self._bookmark_changed()

    def _thread_main(self):
        """ Loop in a worker thread waiting for someone, anyone to press the
        Search button.
        """
        while True:
            self.new_query.wait()
            self.searching = True
            self.new_query.clear()
            self.model.search()
            self.searching = False

    @traits.on_trait_change('bookmarks,bookmarks_items')
    def _update_bookmark_menu(self):
        """ Update the bookmarks menu.
        """
        self.bookmark_menu_group.destroy()
        self.bookmark_menu_group.clear()
        for name, dirs in self.bookmarks:
            self.bookmark_menu_group.append(SelectBookmarkAction(name=name, app=self))
        self.bookmark_menu.changed = True

    def _add_root_changed(self):
        """ Add the given directory to the list of roots.
        """
        current_root = self.current_root.strip()
        if current_root:
            self.other_roots.append(current_root)
        self.current_root = ''

    def _browse_dir_changed(self):
        """ Open a directory browser.
        """
        dlg = QtGui.QFileDialog(self.info.ui.control)
        dlg.selectFile(self.current_root.strip())
        dlg.setFileMode(QtGui.QFileDialog.Directory)
        if dlg.exec_() == QtGui.QDialog.Accepted:
            files = dlg.selectedFiles()
            if len(files) > 0:
                filename = unicode(files[0])
                self.current_root = filename

    @traits.cached_property
    def _get_all_roots(self):
        """ Clean up the list of root directories.
        """
        roots = filter(None, [self.current_root.strip()] + self.other_roots)
        # Uniquify the list in order.
        seen_roots = set()
        all_roots = []
        for d in roots:
            # FIXME: normalize? We might want to display relative paths, so
            # leave it out for now.
            if d not in seen_roots:
                all_roots.append(d)
            seen_roots.add(d)
        return all_roots

    def _search_changed(self):
        """ Perform the search.
        """
        if self.model.regex.strip() != '':
            self.model.roots = self.all_roots
            self.new_query.set()

    def _bookmark_changed(self):
        """ Bookmark the current set of directories.
        """
        dlg = GetAName(title='Enter a name for the bookmark')
        ui = dlg.edit_traits(parent=self.info.ui.control, kind='livemodal')
        if ui.result:
            self.bookmarks.append((dlg.name, self.all_roots))

    def _run_editor(self, filename, lineno=1):
        """ Run the editor on the file with the given line number.
        """
        command = self.command_template.format(filename=filename, lineno=lineno)
        p = subprocess.Popen(shlex.split(command))

    def _results_dclick_changed(self, event):
        """ Open the given line in an editor.
        """
        if event is not None:
            self._run_editor(event.item[0], event.item[1]+1)


def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('dirs', nargs='*')

    args = parser.parse_args()
    qg = QtGrin(model=Searcher())
    if args.dirs:
        qg.other_roots = args.dirs
    else:
        qg.current_root = os.getcwd()
    qg.configure_traits()

if __name__ == '__main__':
    main()