~bzr/ubuntu/jaunty/bzr-explorer/bzr-ppa

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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
# Copyright (C) 2009 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys

from PyQt4 import QtCore, QtGui

try:
    from bzrlib.osutils import parent_directories
except ImportError:
    from bzrlib.plugins.explorer.lib.helpers import parent_directories

from bzrlib.plugins.explorer.lib import kinds
from bzrlib.plugins.explorer.lib.helpers import build_combo_with_labels
from bzrlib.plugins.explorer.lib.i18n import gettext, N_
from bzrlib.plugins.qbzr.lib import treewidget


class WorkingTreeBrowser(QtGui.QDockWidget):

    def __init__(self, action_callback, browse_action, *args):
        self._action_callback = action_callback
        self._browse_action = browse_action
        QtGui.QDockWidget.__init__(self, *args)
        self.setObjectName("WorkingTreeDockWidget")
        self._style = 'qbrowse'
        self._tree = None
        self._branch = None

        # Show either a message or the actual browser
        msg = QtGui.QTextBrowser()
        msg.setText(gettext("No working tree"))
        self._browser = _QBrowseStyleBrowser(action_callback, browse_action, self)
        self._stacked = QtGui.QStackedWidget()
        self._stacked.addWidget(msg)
        self._stacked.addWidget(self._browser)
        self.setWidget(self._stacked)

    def set_tree(self, tree, branch):
        """Display the given working tree.

        :param tree: the WorkingTree to display.
            If None, the view is cleared.
        """
        if tree is None:
            # Show the message
            self._stacked.setCurrentIndex(0)
        else:
            # Show the browser
            self._browser.set_tree(tree, branch)
            if self._style == 'qbrowse':
                index = 1
            else:
                index = 2
            self._stacked.setCurrentIndex(index)
        self._tree = tree
        self._branch = branch

    def refresh(self):
        """Refresh the browser."""
        if self._tree is not None:
            self._browser.refresh()

    def get_style(self):
        return self._style

    def set_style(self, style):
        """Set the style: either qbrowse or classic."""
        self._style = style
        if style == 'classic':
            if self._stacked.count() == 2:
                classic_browser = _ClassicBrowser(self._action_callback,
                    self._browse_action)
                self._stacked.addWidget(classic_browser)
            index = 2
        else:
            index = 1
        self._browser = self._stacked.widget(index)
        self._browser.set_tree(self._tree, self._branch)
        self._stacked.setCurrentIndex(index)

    def set_default_action(self, default_action):
        """Set the default action to either 'open' or 'edit'."""
        self._browser.set_default_action(default_action)


class _ActionPanel(QtGui.QToolBar):

    def __init__(self, action_callback, browse_action, *args):
        self._action_callback = action_callback
        self._browse_action = browse_action
        QtGui.QDialogButtonBox.__init__(self, *args)
        self._root = None
        self._selected_fileinfo = None
        self._button_style = QtCore.Qt.ToolButtonTextUnderIcon

        # Build the buttons and add them to a panel
        self._open_button = self._build_button(
            kinds.icon_for_kind(kinds.OPEN_ACTION),
            gettext("&Open"),
            gettext("Open selected item"),
            self._do_open_file)
        self._edit_button = self._build_button(
            kinds.icon_for_kind(kinds.EDIT_ACTION),
            gettext("&Edit"),
            gettext("Edit selected item"),
            self._do_edit_file)
        self.addSeparator()
        self._build_button(
            kinds.icon_for_kind(kinds.OPEN_FOLDER_ACTION),
            gettext("&Manage"),
            gettext("Open file manager on folder"),
            self._do_open_folder)
        self._build_button(
            kinds.icon_for_kind(kinds.NEW_FILE_ACTION),
            gettext("&New File"),
            gettext("Create a new file"),
            self._do_new_file)
        self._build_button(
            kinds.icon_for_kind(kinds.NEW_FOLDER_ACTION),
            gettext("New &Folder"),
            gettext("Create a new folder"),
            self._do_new_folder)
        self.addSeparator()
        self._build_button(
            self._browse_action.icon(),
            self._browse_action.iconText(),
            self._browse_action.statusTip(),
            self._do_browse_items)
        self.addSeparator()
        self._build_button(
            kinds.icon_for_kind(kinds.COLLAPSE_ALL_ACTION),
            gettext("&Collapse"),
            gettext("Fully collapse tree"),
            self._do_collapse_all)
        self._build_button(
            kinds.icon_for_kind(kinds.EXPAND_ALL_ACTION),
            gettext("&Expand"),
            gettext("Fully expand tree"),
            self._do_expand_all)

    def _build_button(self, icon, text, tooltip, callback, arrow=None):
        button = QtGui.QToolButton()
        button.setText(text)
        if arrow:
            button.setArrowType(arrow)
        else:
            button.setIcon(icon)
        button.setToolTip(tooltip)
        #button.setToolButtonStyle(self._button_style)
        button.setAutoRaise(True)
        #self.addButton(button, QtGui.QDialogButtonBox.ActionRole)
        self.addWidget(button)
        self.connect(button, QtCore.SIGNAL("clicked(bool)"), callback)
        return button

    def _get_folder(self):
        fileinfo = self._selected_fileinfo
        if fileinfo is None:
            folder = self._root
        elif fileinfo.isDir():
            folder = fileinfo.canonicalFilePath()
        else:
            folder = fileinfo.canonicalPath()
        return unicode(folder)

    def _do_browse_items(self):
        self._action_callback("browse", None)

    def _do_open_folder(self):
        self._action_callback("open", self._get_folder())

    def _do_open_file(self):
        fileinfo = self._selected_fileinfo
        path = fileinfo.canonicalFilePath()
        self._action_callback("open", unicode(path))

    def _do_edit_file(self):
        fileinfo = self._selected_fileinfo
        path = fileinfo.canonicalFilePath()
        self._action_callback("edit", unicode(path))

    def _do_new_file(self):
        destination = self._get_folder()
        self._action_callback("new-file", destination)
        self._tree_viewer.refresh()

    def _do_new_folder(self):
        destination = self._get_folder()
        self._action_callback("new-directory", destination)
        self._tree_viewer.refresh()

    def _do_collapse_all(self):
        self._tree_viewer.collapseAll()

    def _do_expand_all(self):
        self._tree_viewer.expandAll()

    def set_viewer(self, tree_viewer):
        self._tree_viewer = tree_viewer

    def set_root(self, path):
        self._root = path

    def set_selection(self, fileinfo, model_index=None):
        self._selected_fileinfo = fileinfo
        self._selected_index = model_index
        edit_is_enabled = True
        if fileinfo is None or fileinfo.isDir():
            edit_is_enabled = False
        self._edit_button.setEnabled(edit_is_enabled)
        self._open_button.setEnabled(edit_is_enabled)


class _FilterPanel(QtGui.QWidget):

    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        self._tree_viewer = None
        self._apply_filter_callback = ''

        # Build the controls
        filter_label = QtGui.QLabel(gettext("Filter:"))
        self._filter_field = QtGui.QLineEdit()
        self._filter_cancel_button = QtGui.QToolButton()
        self._filter_cancel_button.setAutoRaise(True)
        self._filter_cancel_button.setEnabled(False)
        self._filter_cancel_button.setIcon(kinds.icon_for_kind(
            kinds.CANCEL_ACTION))
        self._filter_cancel_button.setToolTip(gettext("Clear the filter"))

        # Connect up the controls to handlers
        self.connect(self._filter_field, QtCore.SIGNAL("textChanged(QString)"),
            self._apply_filter)
        self.connect(self._filter_cancel_button, QtCore.SIGNAL("clicked(bool)"),
            self.clear_filter)

        # Put the controls together
        layout = QtGui.QHBoxLayout()
        layout.addWidget(filter_label)
        layout.addWidget(self._filter_field)
        layout.addWidget(self._filter_cancel_button)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

    def _apply_filter(self, text):
        self._apply_filter_callback(text)
        if text:
            self._filter_cancel_button.setEnabled(True)
        else:
            self._filter_cancel_button.setEnabled(False)
        self._current_filter = text

    def clear_filter(self):
        self._filter_field.setText('')

    def get_filter(self):
        return unicode(self._filter_field.text())

    def set_apply_filter(self, apply_filter_callback):
        self._apply_filter_callback = apply_filter_callback


class _TreeViewer(QtGui.QTreeView):

    def __init__(self, action_callback, selection_callback,
            filter_callback, *args):
        self._action_callback = action_callback
        self._selection_callback = selection_callback
        self._filter_callback = filter_callback
        QtGui.QTreeView.__init__(self, *args)
        self._default_action = "open"

        # Use a proxy model so we can filter on the path.
        self._source_model = _TreeModel()
        self._model = _PathBasedSortFilterProxyModel(self._filter_callback)
        self._model.setSourceModel(self._source_model)
        self.setModel(self._model)
        self._configure_ui()

        # Track the selection
        self.connect(self, QtCore.SIGNAL("doubleClicked(QModelIndex)"),
            self._do_double_clicked)
        sel_model = self.selectionModel()
        self.connect(sel_model,
            QtCore.SIGNAL("currentChanged(QModelIndex,QModelIndex)"),
            self._do_current_changed)

    def _configure_ui(self):
        # Hide all except the Name column
        for i in  range(1, self._model.columnCount()):
            self.setColumnHidden(i, True)
        if getattr(self, 'setHeaderHidden', None):
            self.setHeaderHidden(True)

    def _do_double_clicked(self, model_index):
        fileinfo = self._get_fileinfo(model_index)
        if fileinfo is not None and not fileinfo.isDir():
            path = fileinfo.canonicalFilePath()
            self._action_callback(self._default_action, unicode(path))

    def _do_current_changed(self, model_index, prev_model_index):
        fileinfo = self._get_fileinfo(model_index)
        self._selection_callback(fileinfo, model_index)

    def _get_fileinfo(self, model_index):
        model = model_index.model()
        if model is None:
            fileinfo = None
        else:
            source_index = model.mapToSource(model_index)
            fileinfo = self._source_model.fileInfo(source_index)
        return fileinfo

    def set_tree(self, tree, branch):
        """Change the view to display the given working tree."""
        path = tree.basedir
        source_index = self._source_model.index(path)
        index = self._model.mapFromSource(source_index)
        self.setRootIndex(index)
        self.selectionModel().reset()
        self._model.set_root(path)

    def refresh(self):
        """Refresh the view."""
        self._source_model.refresh()

    def invalidate_filter(self):
        self._model.invalidateFilter()

    def set_default_action(self, default_action):
        """Set the default action to either 'open' or 'edit'."""
        self._default_action = default_action


class _TreeModel(QtGui.QDirModel):

    def __init__(self, parent=None):
        QtGui.QDirModel.__init__(self, parent)
        # Set the sort flags: directories first,
        # on Windows items are case-insensitive
        flags = QtCore.QDir.SortFlags(QtCore.QDir.Name|QtCore.QDir.DirsFirst)
        if sys.platform == 'win32':
            flags |= QtCore.QDir.IgnoreCase
        self.setSorting(flags)


class _PathBasedSortFilterProxyModel(QtGui.QSortFilterProxyModel):

    def __init__(self, filter_callback, parent=None):
        QtGui.QSortFilterProxyModel.__init__(self, parent)
        self._filter_callback = filter_callback
        self._root = None
        self._interesting = None

    def set_root(self, root):
        self._root = root

    def invalidateFilter(self):
        self._text = self._filter_callback()
        if self._text == '':
            self._interesting = None
        else:
            # We only want to show directories containing matching items so
            # we need to do a pass in advance working out what's of interest
            self._source = self.sourceModel()
            root_index = self._source.index(self._root)
            self._interesting = self._find_interesting(self._source,
                root_index, self._text)
        QtGui.QSortFilterProxyModel.invalidateFilter(self)

    def _find_interesting(self, source, root_index, text):
        interesting = set([''])
        directories = set()
        for source_index in self._iter_children(source, root_index):
            fileinfo = source.fileInfo(source_index)
            abspath = unicode(fileinfo.absoluteFilePath())
            relpath = abspath[len(self._root) + 1:]
            if relpath.find(text) >= 0:
                interesting.add(relpath)
                directories.update(parent_directories(relpath))
        interesting.update(directories)
        #print "\ninteresting for %s ...\n%s" % (text, "\n".join(sorted(interesting)))
        return interesting

    def _iter_children(self, source, parent):
        for i in range(0, source.rowCount(parent)):
            index = source.index(i, 0, parent)
            yield index
            for child in self._iter_children(source, index):
                yield child
        
    def filterAcceptsRow(self, source_row, source_parent):
        if self._interesting is None:
            return True
        result = False
        source_index = self._source.index(source_row, 0, source_parent)
        fileinfo = self._source.fileInfo(source_index)
        abspath = unicode(fileinfo.absoluteFilePath())
        if abspath.startswith(self._root):
            # We're inside the tree of interest
            relpath = abspath[len(self._root) + 1:]
            result = relpath in self._interesting
        elif fileinfo.isDir():
            # We're interested if it's a parent of the root
            result = self._root.startswith(abspath)
        return result


class _AbstractBrowser(QtGui.QWidget):

    filter_panel_factory = _FilterPanel
    tree_viewer_factory = _TreeViewer
    action_panel_factory = _ActionPanel

    def __init__(self, action_callback, browse_action, *args):
        self._action_callback = action_callback
        self._browse_action = browse_action
        QtGui.QWidget.__init__(self, *args)

        # Build the ui components
        self._action_panel = self.action_panel_factory(action_callback,
            browse_action)
        self._filter_panel = self.filter_panel_factory()
        self._tree_viewer = self.tree_viewer_factory(action_callback,
            self._action_panel.set_selection, self._filter_panel.get_filter)
        self._action_panel.set_viewer(self._tree_viewer)
        self._filter_panel.set_apply_filter(self._apply_filter)

        # Put them together
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self._filter_panel)
        layout.addWidget(self._tree_viewer)
        layout.addWidget(self._action_panel)
        self.setLayout(layout)

    def set_tree(self, tree, branch):
        """Display the given working tree."""
        self._tree_viewer.set_tree(tree, branch)
        self._action_panel.set_root(tree.basedir)
        self._action_panel.set_selection(None)
        self._filter_panel.clear_filter()

    def refresh(self):
        """Refresh the browser."""
        self._tree_viewer.refresh()

    def set_default_action(self, default_action):
        """Set the default action to either 'open' or 'edit'."""
        self._tree_viewer.set_default_action(default_action)


class _ClassicBrowser(_AbstractBrowser):

    def _apply_filter(self, text):
        self._tree_viewer.invalidate_filter()
        if text:
            # Filtering active. We want to see all matches and
            # this mostly works. It seems to struggle though when
            # the filter gets shorter - maybe a Qt 4.4 bug w.r.t.
            # propagating exactly what's changed to the view?
            self._tree_viewer.expandAll()
        else:
            # Filtering cleared. Restore the initial view with
            # everything collapsed. (If the user has selectively
            # expanded some directories out before filtering,
            # collapsing all here implies losing that setup. We
            # could always remember the expanded directories at
            # the start of filtering and restore them at this
            # point if it proves a problem in practice.)
            self._tree_viewer.collapseAll()
            self._tree_viewer.refresh()


### QBrowse style browser support ###

# The map from filter category to filter flags for TreeFilterProxyModels
_FILTER_FLAGS_MAP = {
    # The flag order is UNCHANGED, CHANGED, UNVERSIONED, IGNORED
    'all':              [True, True, True, True],
    'changed':          [False, True, False, False],
    'versioned':        [True, True, False, False],
    'unversioned':      [False, False, True, False],
    'ignored':          [False, False, True, True],
    'unignored':        [True, True, True, False],
    }

class _QBrowseStyleFilterPanel(QtGui.QWidget):

    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        self._tree_viewer = None

        # Build the controls
        self._category_combo = build_combo_with_labels([
            ('all', gettext("All")),
            ('changed', gettext("Changed")),
            ('versioned', gettext("Versioned")),
            ('unversioned', gettext("Unversioned")),
            ('ignored', gettext("Ignored")),
            ('unignored', gettext("Unignored")),
            ])
        self._category_combo.setCurrentIndex(5)
        self._text_filter = _FilterPanel()

        # Connect up the controls to handlers
        QtCore.QObject.connect(self._category_combo,
            QtCore.SIGNAL("currentIndexChanged(int)"),
            self._apply_category)
        self._text_filter.set_apply_filter(self._apply_text)

        # Put the controls together
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._category_combo)
        layout.addWidget(self._text_filter)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

    def _flags_for_index(self, index):
        category = str(self._category_combo.itemData(index).toString())
        return _FILTER_FLAGS_MAP[category]

    def _apply_category(self, index):
        self._apply_filter_callback(self._flags_for_index(index), True,
            self._text_filter.get_filter(), False)

    def _apply_text(self, text):
        index = self._category_combo.currentIndex()
        self._apply_filter_callback(self._flags_for_index(index), False,
            text, True)

    def clear_filter(self):
        self._text_filter.clear_filter()

    def get_filter(self):
        index = self._category_combo.currentIndex()
        return self._flags_for_index(index), self._text_filter.get_filter()

    def set_apply_filter(self, apply_filter_callback):
        self._apply_filter_callback = apply_filter_callback


class _QBrowseFilterProxyModel(treewidget.TreeFilterProxyModel):
    """Filter a working tree by a text string.

    If the text matches a directory, the directory and all it's contents
    are shown. If the text matches a file, the parent directories and
    the item are shown.

    Note: For efficency, we pre-calculate the interesting entries
    once each time the text is changed. We then simply look up
    each path in the set of interesting paths inside the per-row
    filtering callback.
    """

    def __init__(self, *args):
        treewidget.TreeFilterProxyModel.__init__(self, *args)
        self.text_to_match = None
        self._interesting = None
        self._all_data_loaded = False

    def setTextToMatch(self, text):
        self.text_to_match = text
        self._update_interesting()
        self.invalidateFilter()

    def invalidateFilter(self):
        treewidget.TreeFilterProxyModel.invalidateFilter(self)

    def _update_interesting(self):
        if not self.text_to_match:
            self._interesting = None
            return
        text = self.text_to_match
        interesting = set([''])
        directories = set()
        for path in self._iter_paths():
            if path.find(text) >= 0:
                interesting.add(path)
                directories.update(parent_directories(path))
        interesting.update(directories)
        #print "\ninteresting for %s ...\n%s\n" % (text,
        #    "\n".join(sorted(interesting)))
        self._interesting = interesting

    def _iter_paths(self):
        # The source model loads data lazily. We need everything loaded
        # to find the complete set of paths though
        self._ensure_all_data_loaded()
        return iter(self.source_model.inventory_data_by_path.keys())

    def _ensure_all_data_loaded(self):
        if self._all_data_loaded:
            return
        model = self.source_model
        for id in range(0, len(model.inventory_data)):
            self._load_dirs(model, id)
        self._all_data_loaded = True

    def _load_dirs(self, model, id):
        item_data = model.inventory_data[id]
        if item_data.item.kind == "directory":
            if item_data.children_ids is None:
                # This locks and unlocks the tree each time.
                # I wonder how that impacts performance?
                model.load_dir(id)
            for child_id in item_data.children_ids:
                self._load_dirs(model, child_id)

    def filterAcceptsRow(self, source_row, source_parent):
        result = treewidget.TreeFilterProxyModel.filterAcceptsRow(
            self, source_row, source_parent)
        if result and self._interesting:
            # Apply the text filter (matches found earlier)
            path, kind = self._get_path_info(source_row, source_parent)
            result = path in self._interesting
        return result

    def _get_path_info(self, source_row, source_parent):
        """Return path, kind for a model item."""
        model = self.source_model
        parent_id = source_parent.internalId()
        children_ids = model.inventory_data[parent_id].children_ids
        # Why is this check required?
        if len(children_ids) <= source_row:
            return None, None
        id = children_ids[source_row]
        data = model.inventory_data[id]
        return data.path, data.item.kind


class _QBrowseTreeWidget(treewidget.TreeWidget):

    def __init__(self, *args):
        treewidget.TreeWidget.__init__(self, *args)
        # Patch in a custom FilterProxyModel that handles text filtering
        self.tree_filter_model = _QBrowseFilterProxyModel()
        self.tree_filter_model.setSourceModel(self.tree_model)
        self.setModel(self.tree_filter_model)


class _QBrowseStyleTreeViewer(_QBrowseTreeWidget):

    def __init__(self, action_callback, selection_callback,
            filter_callback, *args):
        self._action_callback = action_callback
        self._selection_callback = selection_callback
        _QBrowseTreeWidget.__init__(self, *args)
        self._default_action = "open"

        # Track the selection
        self.connect(self.selectionModel(),
            QtCore.SIGNAL("currentChanged(QModelIndex,QModelIndex)"),
            self._do_current_changed)

    def do_default_action(self, model_index):
        """Override the handler provided by treewidget.TreeWidget."""
        item_data = self.get_selection_items([model_index])[0]
        fileinfo = QtCore.QFileInfo(item_data.path)
        if fileinfo is not None and not fileinfo.isDir():
            path = fileinfo.canonicalFilePath()
            self._action_callback(self._default_action, unicode(path))

    def _do_current_changed(self, model_index, prev_model_index):
        item_data = self.get_selection_items([model_index])[0]
        fileinfo = QtCore.QFileInfo(item_data.path)
        self._selection_callback(fileinfo, model_index)

    def invalidate_filter(self):
        self.tree_filter_model.invalidateFilter()

    def set_default_action(self, default_action):
        """Set the default action to either 'open' or 'edit'."""
        self._default_action = default_action


class _QBrowseStyleBrowser(_AbstractBrowser):

    filter_panel_factory = _QBrowseStyleFilterPanel
    tree_viewer_factory = _QBrowseStyleTreeViewer

    def _apply_filter(self, flags, flags_changed, text, text_changed):
        if flags_changed:
            self._tree_viewer.tree_filter_model.setFilters(flags)
        if text_changed:
            self._tree_viewer.tree_filter_model.setTextToMatch(text)