File: treeview.py

package info (click to toggle)
treeline 1.4.1-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, wheezy
  • size: 3,692 kB
  • ctags: 1,937
  • sloc: python: 16,152; makefile: 62
file content (491 lines) | stat: -rw-r--r-- 21,703 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python

#****************************************************************************
# treeview.py, provides classes for the main tree view
#
# TreeLine, an information storage program
# Copyright (C) 2006, Douglas W. Bell
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License, either Version 2 or any later
# version.  This program is distributed in the hope that it will be useful,
# but WITTHOUT ANY WARRANTY.  See the included LICENSE file for details.
#*****************************************************************************

import copy
import string
from PyQt4 import QtCore, QtGui
import treedoc
import treeitem
import treemainwin
import optiondefaults
import globalref


class TreeViewItem(QtGui.QTreeWidgetItem):
    """Qt tree item, contains ref to treecore TreeItem"""
    def __init__(self, parent, docItemRef):
        QtGui.QTreeWidgetItem.__init__(self, parent)
        self.docItemRef = docItemRef
        docItemRef.viewData = self
        self.tempSortKey = None
        self.setFlags(self.flags() | QtCore.Qt.ItemIsEditable)
        self.setText(0, docItemRef.title())
        self.childrenLoaded = False
        if self.docItemRef.open:
            self.treeWidget().expandItem(self)
        elif self.docItemRef.childList:
            dummyItem = QtGui.QTreeWidgetItem(self)
        self.setTreeIcon()

    def setTreeIcon(self):
        """Set tree node icon"""
        if globalref.options.boolData('ShowTreeIcons'):
            icon = globalref.treeIcons.getIcon(self.docItemRef.
                                               nodeFormat().iconName, True)
            if icon:
                self.setIcon(0, icon)

    def loadChildren(self):
        """Load child items if this item is open and not yet loaded"""
        if not self.childrenLoaded and self.docItemRef.open:
            self.takeChild(0)    # remove dummy child
            for child in self.docItemRef.childList:
                TreeViewItem(self, child)
            self.childrenLoaded = True

    def loadTempSortKey(self):
        """Calculate a list of ancestor's view indexes for sort keys"""
        indexList = []
        index = self.treeWidget().indexFromItem(self)
        while index.isValid():
            indexList.insert(0, index)
            index = index.parent()
        self.tempSortKey = [index.row() for index in indexList]


class TreeView(QtGui.QTreeWidget):
    """Left pane view of tree structure"""
    def __init__(self, parent=None):
        QtGui.QTreeWidget.__init__(self, parent)
        self.setColumnCount(1)
        self.header().hide()
        self.setRootIsDecorated(True)
        self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
        self.setEditTriggers(QtGui.QAbstractItemView.SelectedClicked)
        self.updateGenOptions()
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setDropIndicatorShown(True)
        self.dragStartPos = None
        self.incremSearchMode = False
        self.incremSearchStr = ''
        self.blockColumnResize = False
        self.editedItem = None
        self.noSelectClickCallback = None
        self.connect(self, QtCore.SIGNAL('itemExpanded(QTreeWidgetItem*)'),
                     self.loadItemChildren)
        self.connect(self, QtCore.SIGNAL('itemCollapsed(QTreeWidgetItem*)'),
                     self.setCollapsed)
        self.connect(self, QtCore.SIGNAL('itemSelectionChanged()'),
                     self.changeSelected)
        self.connect(self,
                     QtCore.SIGNAL('currentItemChanged(QTreeWidgetItem*, '\
                                   'QTreeWidgetItem*)'),
                     self.changeCurrent)

    def updateTree(self):
        """Replace contents of TreeView from the doc"""
        if globalref.docRef.treeFormats.hasConditionals:
            globalref.docRef.root.setDescendantCondTypes()
        origX = self.horizontalScrollBar().value()
        origMaxX = self.horizontalScrollBar().maximum()
        origY = self.verticalScrollBar().value()
        self.blockSignals(True)
        self.blockColumnResize = True
        self.clear()
        self.blockSignals(False)
        item = TreeViewItem(self, globalref.docRef.root)
        if origY <= self.verticalScrollBar().maximum():
            self.verticalScrollBar().setValue(origY)
        self.blockSignals(True)
        if globalref.docRef.selection:
            try:
                self.setCurrentItem(globalref.docRef.selection[-1].viewData)
                globalref.docRef.selection.currentItem = \
                                 globalref.docRef.selection[-1]
                self.scrollToItem(globalref.docRef.selection[-1].viewData)
                for node in globalref.docRef.selection:
                    self.setItemSelected(node.viewData, True)
            except RuntimeError:
                pass  # skip if node doesn't exist anymore
        self.resizeColumnToContents(0)
        self.blockColumnResize = False
        self.blockSignals(False)
        self.horizontalScrollBar().setMaximum(origMaxX)
        self.horizontalScrollBar().setValue(origX)

    def updateSelect(self):
        """Update view selection"""
        origX = self.horizontalScrollBar().value()
        self.blockSignals(True)
        self.clearSelection()
        self.setCurrentItem(globalref.docRef.selection[-1].viewData)
        globalref.docRef.selection.currentItem = globalref.docRef.selection[-1]
        self.scrollToItem(globalref.docRef.selection[-1].viewData)
        for node in globalref.docRef.selection:
            self.setItemSelected(node.viewData, True)
        self.blockSignals(False)
        self.horizontalScrollBar().setValue(origX)

    def updateTreeItem(self, item):
        """Update the title and open status of item"""
        if item.viewData and hasattr(item.viewData, 'treeWidget'):
            try:
                if globalref.docRef.treeFormats.hasConditionals:
                    item.setConditionalType()
                    item.viewData.setTreeIcon()
                item.viewData.setText(0, item.title())
                if item.open != self.isItemExpanded(item.viewData):
                    self.setItemExpanded(item.viewData, item.open)
                self.resizeColumnToContents(0)
            except RuntimeError:
                pass   # skip if doesn't exist anymore due to closed parent

    def loadItemChildren(self, treeViewItem):
        """Ensure children are loaded in response to parent expanding"""
        treeViewItem.docItemRef.open = True
        treeViewItem.loadChildren()
        if not self.blockColumnResize:
            self.resizeColumnToContents(0)

    def updateGenOptions(self):
        """Update tree option settings"""
        self.setIndentation(globalref.options.intData('IndentOffset', 0,
                            optiondefaults.maxIndentOffset))
        if globalref.options.boolData('ClickRename'):
            self.setEditTriggers(QtGui.QAbstractItemView.SelectedClicked)
        else:
            self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)

    def setCollapsed(self, treeViewItem):
        """Set collapsing item to closed"""
        treeViewItem.docItemRef.open = False

    def changeCurrent(self, currentItem, prevItem):
        """Set current item in selection, called from tree signal"""
        if currentItem:
            globalref.docRef.selection.currentItem = currentItem.docItemRef

    def changeSelected(self):
        """Set selection based on signal"""
        selections = self.selectedItems()[:]
        if len(selections) > 1 and \
                 (globalref.options.strData('SelectOrder') == 'tree' or
                  len(selections) > len(globalref.docRef.selection) + 1):
                 # sort if tree order or always for shift-select
            for item in selections:
                item.loadTempSortKey()
            selections.sort(lambda x,y: cmp(x.tempSortKey, y.tempSortKey))
        globalref.docRef.selection.replace([item.docItemRef for item in
                                            selections])
        globalref.updateRightView()

    def edit(self, index, trigger, event):
        """Override to block editing with multiple selection,
           also saves ref to edited item to avoid
           commiting change to wrong item due to next commands"""
        if len(globalref.docRef.selection) == 1:
            result = QtGui.QTreeWidget.edit(self, index, trigger, event)
            if result:
                self.editedItem = globalref.docRef.selection[0]
            return result
        else:
            return False

    def commitData(self, editor):
        """Change tree based on results of edit operation"""
        text = unicode(editor.text())
        item = self.editedItem
        if text and text != item.title() and item.setTitle(text, True):
            QtGui.QTreeWidget.commitData(self, editor)
            self.resizeColumnToContents(0)
            globalref.updateRightView()
        self.editedItem = None

    def findText(self, wordList, forward=True):
        """Select item containing words in searchStr in any field,
           starts with currentItem, return True if found"""
        return globalref.docRef.selection.findText(wordList, forward)

    def treeIncremSearch(self):
        """Begin iterative search"""
        self.incremSearchMode = True
        self.incremSearchStr = ''
        globalref.setStatusBar(_('Search for:'), 0, True)

    def doIncremSearch(self):
        """Search for searchStr in all titles"""
        globalref.setStatusBar(_('Search for: %s') % self.incremSearchStr,
                               0, True)
        if globalref.docRef.selection.findTitleText(self.incremSearchStr):
            globalref.setStatusBar(_('Search for: %s') % self.incremSearchStr,
                                   0, True)
        else:
            globalref.setStatusBar(_('Search for: %s  (not found)') %
                                   self.incremSearchStr, 0, True)

    def treeIncremNext(self):
        """Search for next occurance of increm string"""
        if self.incremSearchStr:
            if globalref.docRef.selection.findNextTitle(self.incremSearchStr,
                                                        True):
                globalref.setStatusBar(_('Next:  %s') % self.incremSearchStr,
                                       0, True)
            else:
                globalref.setStatusBar(_('Next:  %s  (not found)') %
                                       self.incremSearchStr, 0, True)

    def treeIncremPrev(self):
        """Search for previous occurance of increm string"""
        if self.incremSearchStr:
            if globalref.docRef.selection.findNextTitle(self.incremSearchStr,
                                                        False):
                globalref.setStatusBar(_('Previous:  %s') %
                                       self.incremSearchStr, 0, True)
            else:
                globalref.setStatusBar(_('Previous:  %s  (not found)') %
                                       self.incremSearchStr, 0, True)

    def showTypeMenu(self):
        """Show popup menu for changing the item type"""
        self.scrollToItem(self.currentItem())
        rect = self.visualItemRect(self.currentItem())
        pt = self.mapToGlobal(QtCore.QPoint(rect.center().x(), rect.bottom()))
        globalref.mainWin.typeSubMenu.popup(pt)

    def mimeTypes(self):
        """Return list of supported mime types"""
        return ['text/xml']

    def mimeData(self):
        """Return mime data for give TreeWidgetItems"""
        copyFormat = treedoc.TreeDoc.copyFormat
        if len(globalref.docRef.selection) > 1:
            globalref.docRef.treeFormats.addIfMissing(copyFormat)
            root = treeitem.TreeItem(None, copyFormat.name)
            for item in globalref.docRef.selection:
                root.childList.append(copy.copy(item))
                root.childList[-1].parent = root
        else:
            root = globalref.docRef.selection[0]
        text = u'\n'.join(root.branchXml([copyFormat]))
        globalref.docRef.treeFormats.removeQuiet(copyFormat)
        mime = QtCore.QMimeData()
        mime.setData('text/xml', text.encode('utf-8'))
        # mime.setText(text)
        return mime

    def dropMimeData(self, parent, mimeData, isCopy=False):
        """Decode dropped data"""
        mainWin = self.parent().parent().parent().parent()
        oldMainWin = globalref.mainWin
        if globalref.treeControl.duplicateWindows():
            oldMainWin.saveMultiWinTree()
        globalref.updateRefs(mainWin)
        text = unicode(mimeData.data('text/xml'), 'utf-8')
        root, newFormats = globalref.docRef.readXmlStringAndFormat(text)
        if not root:
            globalref.updateRefs(oldMainWin)
            return False
        if root.formatName == treedoc.TreeDoc.copyFormat.name:
            itemList = root.childList
        else:
            itemList = [root]
        undoParents = [parent] + filter(None, [item.parent for item in
                                               globalref.docRef.selection])
        if newFormats:
            globalref.docRef.undoStore.addBranchUndo(undoParents)
            for format in newFormats:
                globalref.docRef.treeFormats.addIfMissing(format)
            globalref.docRef.treeFormats.updateDerivedTypes()
            globalref.docRef.treeFormats.updateUniqueID()
            if treemainwin.TreeMainWin.configDlg:
                treemainwin.TreeMainWin.configDlg.resetParam()
        else:
            globalref.docRef.undoStore.addChildListUndo(undoParents)
        for node in itemList:
            parent.addTree(node)
            if isCopy:
                node.setDescendantUniqueID(True)
        parent.open = True
        globalref.docRef.selection.replace(itemList)
        if newFormats:
            globalref.docRef.treeFormats.updateAutoChoices()
        globalref.updateViewAll()
        globalref.updateRefs(oldMainWin)
        if globalref.treeControl.duplicateWindows():
            oldMainWin.updateMultiWinTree()
        return True

    def mousePressEvent(self, event):
        """Mouse press down event stores position to check for dragging
           and selects item on right-click for popup menu"""
        if self.incremSearchMode:
            self.incremSearchMode = False
            globalref.setStatusBar('')
        clickedItem = self.itemAt(event.pos())
        if not clickedItem:  # skip unselecting click on blank space
            self.dragStartPos = None
            return
        if self.noSelectClickCallback:
            self.noSelectClickCallback(clickedItem.docItemRef)
            self.noSelectClickCallback = None
            return
        if event.button() == QtCore.Qt.LeftButton:
            self.dragStartPos = QtCore.QPoint(event.pos())
        elif event.button() == QtCore.Qt.RightButton:
            return           # stop rename when context menu is used
        origX = self.horizontalScrollBar().value()
        QtGui.QTreeWidget.mousePressEvent(self, event)
        # work around Qt bug - can't set to old value directly?
        self.horizontalScrollBar().setValue(origX + 1)
        self.horizontalScrollBar().setValue(origX)

    def mouseReleaseEvent(self, event):
        """Mouse release event for popup menus"""
        self.dragStartPos = None
        clickedItem = self.itemAt(event.pos())
        if not clickedItem:  # skip unselecting click on blank space
            return
        QtGui.QTreeWidget.mouseReleaseEvent(self, event)

    def contextMenuEvent(self, event):
        """Show popup menu"""
        if event.reason() == QtGui.QContextMenuEvent.Mouse:
            clickedItem = self.itemAt(event.pos())
            if not clickedItem:
                event.ignore()
                return
            if not self.isItemSelected(clickedItem):
                self.blockSignals(True)
                self.clearSelection()
                self.blockSignals(False)
                self.setItemSelected(clickedItem, True)
            pos = event.globalPos()
        else:       # shown for menu key or other reason
            if not globalref.docRef.selection:
                event.ignore()
                return
            selectList = globalref.docRef.selection[:]
            if globalref.docRef.selection.currentItem in selectList:
                selectList.insert(0, globalref.docRef.selection.currentItem)
            posList = [self.visualItemRect(item.viewData).bottomLeft() for
                       item in selectList]
            posList = [pos for pos in posList if self.rect().contains(pos)]
            if not posList:
                posList = [QtCore.QPoint(0, 0)]
            pos = self.mapToGlobal(posList[0])
        parentList = [item for item in globalref.docRef.selection if
                      item.childList]
        if parentList:
            menu = globalref.mainWin.parentPopup
        else:
            menu = globalref.mainWin.childPopup
        menu.popup(pos)
        event.accept()

    def mouseMoveEvent(self, event):
        """Mouse move event to start drag & drop"""
        if event.buttons() == QtCore.Qt.LeftButton and self.dragStartPos and \
                globalref.docRef.selection and \
                (event.pos() - self.dragStartPos).manhattanLength() > \
                QtGui.QApplication.startDragDistance() and \
                globalref.options.boolData('DragTree'):
            oldSelect = globalref.docRef.selection[:]
            drag = QtGui.QDrag(self)
            drag.setMimeData(self.mimeData())
            dropAction = drag.start(QtCore.Qt.MoveAction |
                                    QtCore.Qt.CopyAction)
            if dropAction == QtCore.Qt.MoveAction:
                if drag.target() == None:  # move to different session
                    if globalref.docRef.root in oldSelect:
                        return   # can't delete root
                    undoParents = filter(None, [item.parent for item in
                                                globalref.docRef.selection])
                    globalref.docRef.undoStore.addChildListUndo(undoParents)
                    globalref.docRef.selection.replace([undoParents[0]])
                elif filter(None, [node.hasDescendant(globalref.docRef.
                                                      selection[0])
                                   for node in oldSelect]):
                    return  # don't delete if drag to descendant
                for item in oldSelect:
                    item.delete()
                globalref.updateViewAll()

    def dragMoveEvent(self, event):
        """Drag move event to set proper (+) or (-) for drag & drop"""
        event.setDropAction(self.dropActionFromEvent(event))
        event.accept()

    def dropEvent(self, event):
        """Drop event for drag & drop"""
        parentItem = self.itemAt(event.pos())
        if parentItem and (not self.isItemSelected(parentItem) or
                           not event.source()):
            event.setDropAction(self.dropActionFromEvent(event))
            if self.dropMimeData(parentItem.docItemRef, event.mimeData(),
                                 event.dropAction() == QtCore.Qt.CopyAction):
                event.accept()
                return
        event.ignore()

    def dropActionFromEvent(self, event):
        """Return appropriate action based on modifier keys and drag source"""
        if event.keyboardModifiers() == QtCore.Qt.ControlModifier:
            action = QtCore.Qt.CopyAction
        elif event.keyboardModifiers() == QtCore.Qt.ShiftModifier:
            action = QtCore.Qt.MoveAction
        elif event.source() == self:
            action = QtCore.Qt.MoveAction
        else:
            action = QtCore.Qt.CopyAction
        return action

    def focusOutEvent(self, event):
        """Stop incremental search on focus loss"""
        if self.incremSearchMode:
            self.incremSearchMode = False
            globalref.setStatusBar('')
        QtGui.QTreeWidget.focusOutEvent(self, event)

    def keyPressEvent(self, event):
        """Bind keys to functions"""
        keyText = unicode(event.text())
        if self.incremSearchMode:
            if event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter,
                               QtCore.Qt.Key_Escape):
                self.incremSearchMode = False
                globalref.setStatusBar('')
            elif event.key() == QtCore.Qt.Key_Backspace and \
                                self.incremSearchStr:
                self.incremSearchStr = self.incremSearchStr[:-1]
                self.doIncremSearch()
            elif keyText and keyText in string.printable:
                self.incremSearchStr += keyText
                self.doIncremSearch()
            event.accept()
        elif event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter) and \
                event.modifiers() == QtCore.Qt.NoModifier and \
                globalref.options.boolData('InsertOnEnter') and \
                self.state() != QtGui.QAbstractItemView.EditingState:
            if len(globalref.docRef.selection) == 1 and \
                       not globalref.docRef.selection[0].parent:
                globalref.mainWin.editAddChild()  # only root selected
            else:
                globalref.mainWin.editInAfter()
            event.accept()
        else:
            origX = self.horizontalScrollBar().value()
            QtGui.QTreeWidget.keyPressEvent(self, event)
            self.horizontalScrollBar().setValue(origX)