# -*- coding: utf-8 -*-

# Copyright (c) 2003 - 2006 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing the helpbrowser.
"""

from qt import *

from KdeQt import KQMessageBox

import Preferences

class HelpBrowser(QTextBrowser):
    """
    Class implementing the helpbrowser widget.
    
    This is a subclass of the Qt QTextBrowser to implement a
    custimized setSource method. The implementation was
    influenced by Qt Assistant, which is copyright by Trolltech AS.
    """
    def __init__(self, parent = None, name = None):
        """
        Constructor
        
        @param parent parent widget of this window (QWidget)
        @param name name of this window (string or QString)
        """
        QTextBrowser.__init__(self, parent, name)
        
        self.mw = parent
        self.processes = []
        self.lastAnchor = QString()
        self.shiftPressed = 0
        
    def setSource(self, name):
        """
        Method used to set the source to be displayed.
        
        This method is overridden from QTextBrowser.
        
        @param name filename to be shown (QString)
        """
        if name.isEmpty():
            return
            
        if name.startsWith("http://") or \
           name.startsWith("https://") or \
           name.startsWith("ftp://"):
            # display in an external browser, if one is set
            webbrowser = Preferences.getHelp("Webbrowser")
            if webbrowser.isEmpty():
                KQMessageBox.information(self,
                    self.trUtf8("Helpviewer"),
                    self.trUtf8("""Currently no Web browser is selected."""
                                """ Please use the preferences dialog to specify one."""),
                    self.trUtf8("&OK"),
                    QString.null,
                    QString.null,
                    0, -1)
                return
                
            proc = QProcess()
            proc.addArgument(webbrowser)
            proc.addArgument(name)
            
            self.connect(proc, SIGNAL('processExited()'), self.procExited)
            if proc.start():
                self.processes.append(proc)
            return
        
        if self.shiftPressed:
            # open in a new window
            self.removeSelection()
            self.mw.handleNewWindow(name)
            self.shiftPressed = 0
            return
        
        # only show file, if it is a local file
        u = QUrl(QUrl(self.context()), name)
        if not u.isLocalFile():
            KQMessageBox.warning(None,
                self.trUtf8("Helpviewer"),
                self.trUtf8("""<p>Can't load and display non-local file <b>%1</b>.</p>""").arg(name),
                self.trUtf8("&OK"),
                QString.null,
                QString.null,
                0, -1)
            return
            
        if name.endsWith(".pdf") or \
           name.endsWith(".PDF"):
            # display in an external PDF viewer, if one is set
            pdfviewer = Preferences.getHelp("Pdfviewer")
            if pdfviewer.isEmpty():
                KQMessageBox.information(self,
                    self.trUtf8("Helpviewer"),
                    self.trUtf8("""Currently no PDF viewer is selected.
Please use the preferences dialog to specify one."""),
                    self.trUtf8("&OK"),
                    QString.null,
                    QString.null,
                    0, -1)
                return
                
            proc = QProcess()
            proc.addArgument(pdfviewer)
            name.replace("file:", "") # remove protocol, if there is one
            proc.addArgument(name)
            
            self.connect(proc, SIGNAL('processExited()'), self.procExited)
            if proc.start():
                self.processes.append(proc)
            return
           
        # now show it
        QTextBrowser.setSource(self, name)

    def procExited(self):
        """
        Private slot to handle the processExited signal.
        """
        proc = self.sender()
        if proc is not None:
            self.processes.remove(proc)
            
    def createPopupMenu(self, pos):
        """
        Method called to create a context menu.
        
        This method is overridden from QTextBrowser.
        
        @param pos document position (QPoint)
        """
        menu = QPopupMenu(self)
        
        self.lastAnchor = self.anchorAt(pos)
        if not self.lastAnchor.isEmpty():
            fi = QFileInfo(self.source())
            if not fi.dirPath(1).isEmpty():
                self.lastAnchor = QFileInfo("%s/%s" % \
                    (unicode(fi.dirPath(1)), unicode(self.lastAnchor))).absFilePath()
            
            menu.insertItem(self.trUtf8("Open Link in New Window\tShift+LMB"),
                self.openLinkInNewWindow)
        
        self.mw.newAct.addTo(menu)
        menu.insertSeparator()
        self.mw.backAct.addTo(menu)
        self.mw.forwardAct.addTo(menu)
        self.mw.homeAct.addTo(menu)
        menu.insertSeparator()
        self.mw.zoomInAct.addTo(menu)
        self.mw.zoomOutAct.addTo(menu)
        menu.insertSeparator()
        self.mw.copyAct.addTo(menu)
        self.mw.findAct.addTo(menu)
        
        return menu
        
    def openLinkInNewWindow(self):
        """
        Method used to called by the context menu to open a link in a new window.
        """
        if self.lastAnchor.isEmpty():
            return
            
        oldShiftPressed = self.shiftPressed
        self.shiftPressed = 1
        self.setSource(self.lastAnchor)
        self.shiftPressed = oldShiftPressed
        
    def keyPressEvent(self, evt):
        """
        Method called by a key press.
        
        This method is overridden from QTextBrowser.
        
        @param evt the key event (QKeyEvent)
        """
        self.shiftPressed = (evt.key() == Qt.Key_Shift)
        QTextBrowser.keyPressEvent(self, evt)
        
    def keyReleaseEvent(self, evt):
        """
        Method called by a key release.
        
        This method is overridden from QTextBrowser.
        
        @param evt the key event (QKeyEvent)
        """
        self.shiftPressed = 0
        QTextBrowser.keyReleaseEvent(self, evt)
