#!/usr/bin/python
###########################################################################
# kdeapp - description                                                    #
# ------------------------------                                          #
# begin     : Fri Jun 27 2005                                             #
# copyright : (C) 2005 by AUTHOR                                          #
# email     : your@email.com                                              #
#                                                                         #
###########################################################################
#                                                                         #
#   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.                                   #
#                                                                         #
###########################################################################

from qt import *
from kdecore import *
from kdeui import *
import sys
from prefdialog import *
from kdeappview import *

description = "A KDE Application"
version = "0.1";

class KdeApp(KMainWindow):
    def __init__(self):
        KMainWindow.__init__(self,None,"KdeApp")

        self._view = KdeAppView(self)
        self._printer = None

        # accept dnd
        self.setAcceptDrops(True)

        # tell the KMainWindow that this is indeed the main widget
        self.setCentralWidget(self._view)

        # then, setup our actions
        self._setupActions()

        # and a status bar
        self.statusBar().show()

        # Apply the create the main window and ask the mainwindow to
        # automatically save settings if changed: window size, toolbar
        # position, icon size, etc.  Also to add actions for the statusbar
        # toolbar, and keybindings if necessary.
        self.setAutoSaveSettings()

        # allow the view to change the statusbar and caption
        self.connect(self._view, PYSIGNAL("signalChangeStatusbar"), self.changeStatusbar)
        self.connect(self._view, PYSIGNAL("signalChangeCaption"), self.changeCaption)

    def load(self,url):
        target = QString()
        # the below code is what you should normally do.  in this
        # example case, we want the url to our own.  you probably
        # want to use this code instead for your app
    
        if False:
            # download the contents
            if KIO.NetAccess.download(url, target):
                # set our caption
                self.setCaption(url)
        
                # load in the file (target is always local)
                self.loadFile(target)
        
                # and remove the temp file
                KIO.NetAccess.removeTempFile(target)
    
        self.setCaption(url.prettyURL())
        self._view.openURL(url)


    def _setupActions(self):
        global kapp
        KStdAction.openNew(self.fileNew, self.actionCollection())
        KStdAction.open(self.fileOpen, self.actionCollection())
        KStdAction.save(self.fileSave, self.actionCollection())
        KStdAction.saveAs(self.fileSaveAs, self.actionCollection())
        KStdAction.print_(self.filePrint, self.actionCollection())
        KStdAction.quit(kapp.quit, self.actionCollection())
        
        self._toolbarAction = KStdAction.showToolbar(self.optionsShowToolbar, self.actionCollection())
        self._statusbarAction = KStdAction.showStatusbar(self.optionsShowStatusbar, self.actionCollection())
        KStdAction.keyBindings(self.optionsConfigureKeys, self.actionCollection())

        KStdAction.configureToolbars(self.optionsConfigureToolbars, self.actionCollection())
        KStdAction.preferences(self.optionsPreferences, self.actionCollection())
    
        # this doesn't do anything useful.  it's just here to illustrate
        # how to insert a custom menu and menu item
        custom = KAction(i18n("Cus&tom Menuitem"), KShortcut(),
                    self.optionsPreferences,
                    self.actionCollection(), "custom_action")
        self.createGUI()

    def _saveProperties(self,config):
        # the 'config' object points to the session managed
        # config file.  anything you write here will be available
        # later when this app is restored
    
        if not self._view.currentURL().isEmpty():
            config.writeEntry("lastURL", self._view.currentURL())

    def _readProperties(self,config):
        # the 'config' object points to the session managed
        # config file.  this function is automatically called whenever
        # the app is being restored.  read in here whatever you wrote
        # in 'saveProperties'
    
        url = config.readPathEntry("lastURL")
    
        if not url.isEmpty():
            self._view.openURL(KURL(url))

    def dragEnterEvent(self,event):
        # accept uri drops only
        event.accept(KURLDrag.canDecode(event))

    def dropEvent(self,event):
        # this is a very simplistic implementation of a drop event.  we
        # will only accept a dropped URL.  the Qt dnd code can do *much*
        # much more, so please read the docs there
        urls = KURL.List()
    
        # see if we can decode a URI.. if not, just ignore it
        if KURLDrag.decode(event, urls) and not urls.isEmpty():
            # okay, we have a URI.. process it
            url = urls.first()
    
            # load in the file
            self.load(url)

    def fileNew(self):
        # this slot is called whenever the File->New menu is selected,
        # the New shortcut is pressed (usually CTRL+N) or the New toolbar
        # button is clicked
    
        # create a new window
        KdeApp().show()

    def fileOpen(self):
        # this slot is called whenever the File->Open menu is selected,
        # the Open shortcut is pressed (usually CTRL+O) or the Open toolbar
        # button is clicked
    
        ## this brings up the generic open dialog
        #KURL url = KURLRequesterDlg::getURL(QString::null, this, i18n("Open Location") );
    
        # standard filedialog
        url = KFileDialog.getOpenURL(None, One, self, i18n("Open Location"))
        if not url.isEmpty():
            self._view.openURL(url)

    def fileSave(self):
        # this slot is called whenever the File->Save menu is selected,
        # the Save shortcut is pressed (usually CTRL+S) or the Save toolbar
        # button is clicked
    
        # save the current file
        pass

    def fileSaveAs(self):
        # this slot is called whenever the File->Save As menu is selected,
        file_url = KFileDialog.getSaveURL()
        if not file_url.isEmpty() and file_url.isValid():
            # save your info, here
            pass


    def filePrint(self):
        # this slot is called whenever the File->Print menu is selected,
        # the Print shortcut is pressed (usually CTRL+P) or the Print toolbar
        # button is clicked
        if self._printer is None:
            self._printer = KPrinter()
            
        if self._printer.setup(self):
            # setup the printer.  with Qt, you always "print" to a
            # QPainter.. whether the output medium is a pixmap, a screen,
            # or paper
            p = QPainter()
            p.begin(self._printer)
    
            # we let our view do the actual printing
            metrics = QPaintDeviceMetrics(m_printer)
            self._view.print_(p, metrics.height(), metrics.width())
    
            # and send the result to the printer
            p.end();

    def optionsPreferences(self):
        # popup some sort of preference dialog, here
        dlg = PreferencesDialog()
        if dlg.exec_loop():
            # redo your settings
            pass

    def optionsShowToolbar(self):
        # this is all very cut and paste code for showing/hiding the
        # toolbar
        if self._toolbarAction.isChecked():
            self.toolBar().show()
        else:
            self.toolBar().hide()

    def optionsShowStatusbar(self):
        # this is all very cut and paste code for showing/hiding the
        # statusbar

        if self._statusbarAction.isChecked():
            self.statusBar().show()
        else:
            self.statusBar().hide()

    def optionsConfigureKeys(self):
        KKeyDialog.configure(self.actionCollection())

    def optionsConfigureToolbars(self):
        # use the standard toolbar editor
        self.saveMainWindowSettings(KGlobal.config())

    def newToolbarConfig(self):
        # this slot is called when user clicks "Ok" or "Apply" in the toolbar editor.
        # recreate our GUI, and re-apply the settings (e.g. "text under icons", etc.)
        self.createGUI()
        self.applyMainWindowSettings(KGlobal.config())

    def changeStatusbar(self,text):
        # display the text on the statusbar
        self.statusBar().message(text)

    def changeCaption(self,text):
        # display the text on the caption
        self.setCaption(text)


options = [ ("+[URL]", "Document to open", "") ]

def main():
    global kapp,version,description,options

    aboutdata = KAboutData("kdeapp", "KdeApp", version, description, \
        KAboutData.License_GPL, "(C) 2005 AUTHOR", None, None, "your@email.com")
    aboutdata.addAuthor("AUTHOR", None, "your@email.com")
    KCmdLineArgs.init(sys.argv,aboutdata)
    KCmdLineArgs.addCmdLineOptions(options)
    kapp = KApplication()
    
    # register ourselves as a dcop client
    kapp.dcopClient().registerAs(kapp.name(), False)

    # see if we are starting with session management
    if kapp.isRestored():
        n = 1
        while KMainWindow.canBeRestored(n):
            KdeApp().restore(n)
            n += 1
    else:
        # no session.. just start up normally
        args = KCmdLineArgs.parsedArgs()
        if args.count() == 0:
            widget = KdeApp()
            widget.show()
        else:
            i = 0
            for i in range(args.count()):
                widget = KdeApp()
                widget.show()
                widget.load(args.url(i))

        args.clear()

    return kapp.exec_loop()
main()
