#!/usr/bin/env python #**************************************************************************** # plugininterface.py, provides an interface class for plugin extension modules # # TreeLine, an information storage program # Copyright (C) 2005, Douglas W. Bell # # This is free software; you can redistribute it and/or modify it under the # terms of the GNU General Public License, Version 2. This program is # distributed in the hope that it will be useful, but WITTHOUT ANY WARRANTY. #***************************************************************************** """Plugin Interface Rules Plugins are python files located in the plugins directory (/lib/treeline/plugins/ on Linux or TreeLine\lib\plugins\ on Windows). Plugins must define a function named "main" that takes an instance of the PluginInterface class as its only argument. The function should initialize the plugin. It is called after the TreeLine GUI is initialized (with a new file) but before any other files are opened. The return value of the function is stored by TreeLine to avoid garbage collection of the reference (although this shouldn't be necessary for non-trivial plugins). There should be a module doc string defined by the plugin. The first line is used as the plugin listing in Help->About Plugins. It should contain the plugin name and a very brief description. To avoid problems with plugins breaking when TreeLine is revised, the plugin API is restricted to the methods of the PluginInterface class. References from within the method code and elsewhere in TreeLine code should not be used. Exceptions to this rule include certain data members of node objects (childList, parent and data) and the interface's mainWin data member (to be used only as a parent for new Qt objects). Of course, if a method returns a Qt object, the normal Qt API is available. There are methods that setup callback functions for various TreeLine operations. Probably the most useful is the view update callback, which is called any time something changes in TreeLine requiring view or control availability updates. """ from treedoc import ReadFileError, PasswordError from nodeformat import NodeFormat import globalref from qt import QPixmap class PluginInterface: """Defines the available interface for the plugins""" def __init__(self, mainWin): self.mainWin = mainWin # may be used in plugin as widget parent only self.viewUpdateCallbacks = [] # internal use only self.dataChangeCallbacks = [] # internal use only self.fileNewCallbacks = [] # internal use only self.fileOpenCallbacks = [] # internal use only self.fileSaveCallbacks = [] # internal use only #************************************************************************* # Node Interfaces: #************************************************************************* def getCurrentNode(self): """Return a reference to the currently active node""" return globalref.docRef.selection.currentItem def getSelectedNodes(self): """Return a list of currently selected nodes""" return globalref.docRef.selection[:] def changeSelection(self, newSelectList): """Change tree selections, last item in newSelectList becomes the current item, views are updated""" globalref.docRef.selection.change(newSelectList) def getRootNode(self): """Return a reference to the root node""" return globalref.docRef.root def getNodeChildList(self, node): """Return a list of node's child nodes, this method provided for completeness - node.childList may be used directly""" return node.childList def getNodeParent(self, node): """Return node's parent node or None if node is root, this method provided for completeness - node.parent may be used directly""" return node.parent def getNodeDescendantList(self, node): """Return a list containing the current node and all of its descendant nodes""" return node.descendantList(True) def addChildNode(self, parent, text=u'New', pos=-1): """Add new child before position, -1 is at end - return new item""" return parent.addChild(text, pos) def insertSibling(self, siblingNode, text=u'New', inAfter=False): """Add new sibling before or after sibling - return new item""" return siblingNode.insertSibling(text, inAfter) def setNodeOpenClosed(self, node, setOpen=True): """Open children in tree if open is True, close children if False""" node.open = setOpen def getNodeDataDict(self, node): """Return a dictionary containing the node's raw field data field names are the dictionary keys, the data is unicode text, this method provided for completeness - node.data may be used directly""" return node.data def getNodeTitle(self, node): """Return the formatted unicode text for the node's title as shown in the tree""" return node.title() def setNodeTitle(self, node, titleText): """Set the node's title to titleText by modifying the field data used in the title format, returns True if successful, False otherwise""" return node.setTitle(titleText) def getNodeOutput(self, node, lineSep='
\n'): """Return the formatted unicode text for the node's output, separate lines using lineSep""" return lineSep.join(node.formatText()) def getChildNodeOutput(self, node, lineSep='
\n'): """Return the formatted unicode text for the node children's output, separate lines using lineSep""" return lineSep.join(node.formatChildText()) def getFieldOutput(self, node, fieldName): """Return formatted text for the given fieldName data""" field = node.nodeFormat.findField(fieldName) if field: return node.nodeFormat.fieldText(field, node) return '' def getNodeFormatName(self, node): """Return the format type name for the given node""" return node.nodeFormat.name def setNodeFormat(self, node, formatName): """Set the given node to the given node format type""" newFormat = globalref.docRef.treeFormats.findFormat(formatName) if newFormat: node.nodeFormat = newFormat def setDataChangeCallback(self, callbackFunc): """Set callback function to be called every time a node's dictionary data is changed. The callbackFunc must take two arguments: the node being changed and a list of changed fields""" self.dataChangeCallbacks.append(callbackFunc) #************************************************************************* # Format Interfaces: #************************************************************************* def getNodeFormatNames(self): """Return text list of available node format names""" return globalref.docRef.treeFormats.nameList(True) def newNodeFormat(self, formatName, defaultFieldName='Name'): """Create a new node format, names must only contain characters [a-zA-Z0-9_.-]. If defaultFieldName, a text field is created and added to the title line and the first output line""" globalref.docRef.treeFormats.append(NodeFormat(formatName, {}, \ defaultFieldName)) def copyFileFormat(self, fileRef, password=''): """Copy the configuration from another TreeLine file, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined), passord is optional - used to open an encrypted TreeLine file, returns True/False on success/failure""" try: globalref.docRef.treeFormats.configCopy(fileRef, password) return True except (PasswordError, IOError, UnicodeError, ReadFileError): return False def getFormatIconName(self, formatName): """Return the node format's currently set icon name, a default setting will return an empty string, blank will return 'NoIcon'""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: return format.iconName return '' def setFormatIconName(self, formatName, iconName): """Set the node format's icon to iconName, an empty string or unknown icon name will get the default icon, use 'NoIcon' to get a blank""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: format.iconName = iconName def addTreeIcon(self, name, icon): """Add an icon to those available for use in the tree, icon data can be in any image format supported by Qt, if name matches one already loaded, the earlier one is replaced""" globalref.treeIcons[name] = QPixmap(icon) def getTitleLineFormat(self, formatName): """Return the node format's title formatting line""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: return format.getLines()[0] return '' def setTitleLineFormat(self, formatName, newLine): """Set the node format's title formatting line to newLine""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: format.insertLine(newLine, 0) def getOutputFormatLines(self, formatName): """Return a list of the node format's output formatting lines""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: return format.getLines()[1:] return [] def setOutputFormatLines(self, formatName, lineList): """Set the node format's output formatting lines to lineList""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: format.lineList = format.lineList[:1] for line in lineList: format.addLine(line) def getFormatFieldNames(self, formatName): """Return a list of the node format's field names""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: return format.fieldNames() return [] def addNewFormatField(self, formatName, fieldName, fieldType='Text'): """Add a new field to the node format, type should be one of: Text, Number, Choice, Combination, AutoChoice, Date, Time, Boolean, URL, Path, Email, InternalLink, ExecuteLink, Picture""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: format.addNewField(fieldName, {'type': fieldType}) def getFormatFieldType(self, formatName, fieldName): """Return the type of the given field in the given format""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: return field.typeName def changeFormatFieldType(self, formatName, fieldName, newFieldType): """Change the type of the given field in the given format, type should be one of: Text, Number, Choice, Combination, AutoChoice, Date, Time, Boolean, URL, Path, Email, InternalLink, ExecuteLink, Picture""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: field.changeType(newFieldType) def getFormatFieldFormat(self, formatName, fieldName): """Return the format code string of the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: return field.format def setFormatFieldFormat(self, formatName, fieldName, newFieldFormat): """Change the format code string of the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: field.format = newFieldFormat field.initFormat() def getFormatFieldExtraText(self, formatName, fieldName): """Return a tuple of the prefix and suffix text of the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: return (field.prefix, field.suffix) def setFormatFieldExtraText(self, formatName, fieldName, newPrefix='', newSuffix=''): """Set the format prefix and suffix text of the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: field.prefix = newPrefix field.suffix = newSuffix def getFormatFieldHtmlProp(self, formatName, fieldName): """Return True if the given field is set to use HTML, False for plain text""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: return field.html def setFormatFieldHtmlProp(self, formatName, fieldName, htmlProp=True): """Change the HTML handling of the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: field.html = htmlProp def getFormatFieldNumLines(self, formatName, fieldName): """Return the number of lines set for the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: return field.numLines def setFormatFieldNumLines(self, formatName, fieldName, numLines): """Set the number of lines set for the given field""" format = globalref.docRef.treeFormats.findFormat(formatName) if format: field = format.findField(fieldName) if field: field.numLines = numLines #************************************************************************* # View Interfaces: #************************************************************************* def updateViews(self): """Refresh the tree view and the current right-side views to reflect current data""" globalref.updateViewAll() def setViewUpdateCallback(self, callbackFunc): """Set callback function to be called after every TreeLine view update and control availability change (it is called often but is a good way to check for specific changes)""" self.viewUpdateCallbacks.append(callbackFunc) #************************************************************************* # File Interfaces: #************************************************************************* def openFile(self, fileRef, importOnFail=True, addToRecent=True): """Open file given by fileRef interactively (QMessageBox on failure), fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined), if importOnFail and not a TreeLine file, will prompt for import type, if addToRecent, will add filename to recently used file list""" self.mainWin.openFile(fileRef, importOnFail, addToRecent) def newFile(self): """Start a new file""" self.mainWin.fileNew() def readFile(self, fileRef, password=''): """Open TreeLine file given by fileRef non-interactively, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined), returns True/False on success/failure""" if password: if hasattr(fileRef, 'read'): fileName = unicode(fileRef.name, globalref.docRef.localEncoding) else: fileName = fileRef globalref.docRef.setPassword(fileName, password) try: globalref.docRef.readFile(fileRef) return True except (PasswordError, IOError, UnicodeError): return False def saveFile(self, fileRef): """Save TreeLine file to fileRef interactively (QMessageBox on failure), fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined)""" self.mainWin.saveFile(fileRef) def writeFile(self, fileRef, password=''): """Save TreeLine file to fileRef non-interactively, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined), returns True/False on success/failure""" if password: if hasattr(fileRef, 'read'): fileName = unicode(fileRef.name, globalref.docRef.localEncoding) else: fileName = fileRef globalref.docRef.setPassword(fileName, password) try: globalref.docRef.writeFile(fileRef) return True except IOError: return False def getDocModified(self): """Return True if the current document is marked as modified, False otherwise""" return globalref.docRef.modified def setDocModified(self, value): """A value of True sets the document status to modified, a value of False is unmodified""" globalref.docRef.modified = value globalref.updateViewMenuStat() def setFileNewCallback(self, callbackFunc): """Set callback function to be called after a new file is started""" self.fileNewCallbacks.append(callbackFunc) def setFileOpenCallback(self, callbackFunc): """Set callback function to be called after opening a file""" self.fileOpenCallbacks.append(callbackFunc) def setFileSaveCallback(self, callbackFunc): """Set callback function to be called after a file is saved""" self.fileSaveCallbacks.append(callbackFunc) def exportHtml(self, fileRef, includeRoot=True, openOnly=False, indent=20, \ addHeader=False): """Export current branch to single-column HTML, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined), remaining parameters are options, returns True on success, False on failure""" try: globalref.docRef.exportHtml(fileRef, self.getCurrentNode(), \ includeRoot, openOnly, indent, addHeader) return True except IOError: return False def exportXslt(self, fileRef, includeRoot=True, indent=20): """Export XSLT file for the current formatting, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined), returns True on success, False on failure""" try: globalref.docRef.exportXslt(fileRef, includeRoot, indent) self.updateViews() return True except IOError: return False def exportTrlSubtree(self, fileRef): """Export current branch as a TreeLine subtree, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined) returns True on success, False on failure""" try: globalref.docRef.exportTrlSubtree(fileRef, self.getCurrentNode()) return True except IOError: return False def exportTable(self, fileRef): """Export current item's children as a table of data, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined) returns True on success, False on failure""" try: globalref.docRef.exportTable(fileRef, self.getCurrentNode()) return True except IOError: return False def exportTabbedTitles(self, fileRef, includeRoot=True, openOnly=False): """Export current branch to tabbed text titles, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined) returns True on success, False on failure""" try: globalref.docRef.exportTabbedTitles(fileRef, \ self.getCurrentNode(), \ includeRoot, openOnly) return True except IOError: return False def exportXbelBookmarks(self, fileRef): """Export current branch to XBEL format bookmarks, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined) returns True on success, False on failure""" try: globalref.docRef.exportXbel(fileRef, self.getCurrentNode()) return True except IOError: return False def exportHtmlBookmarks(self, fileRef): """Export current branch to HTML format bookmarks, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined) returns True on success, False on failure""" try: globalref.docRef.exportHtmlBookmarks(fileRef, self.getCurrentNode()) return True except IOError: return False def exportGenericXml(self, fileRef): """Export current branch to generic XML (non-TreeLine) file, fileRef is either a file path string or a file-like object (if it is a file-like object, fileRef.name must be defined) returns True on success, False on failure""" try: globalref.docRef.exportGenericXml(fileRef, self.getCurrentNode()) return True except IOError: return False #************************************************************************* # Menu Interfaces: #************************************************************************* def getMenuBar(self): """Return the main window's top menu bar (QMenuBar)""" return self.mainWin.menuBar() def getPulldownMenu(self, index): """Return top pulldown menu at position index (QPopupMenu), return None if index is not valid""" try: return self.mainWin.pulldownMenuList[index] except IndexError: return None #************************************************************************* # Internal methods (not for plugin use): #************************************************************************* def execCallback(self, funcList, *args): """Call functions in funcList with given args if any""" for func in funcList: func(*args)