summaryrefslogtreecommitdiffstats
path: root/lib/kross/main/scriptguiclient.cpp
blob: a90c3d9d468b38d25031f5efad483864614eee5f (plain)
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
/***************************************************************************
 * scriptguiclient.cpp
 * This file is part of the KDE project
 * copyright (C) 2005 by Sebastian Sauer (mail@dipe.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library 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
 * Library General Public License for more details.
 * You should have received a copy of the GNU Library General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 ***************************************************************************/

#include "scriptguiclient.h"
#include "manager.h"
#include "../api/interpreter.h"
#include "wdgscriptsmanager.h"

#include <kapplication.h>
#include <kpopupmenu.h>
#include <kstandarddirs.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kurl.h>
#include <ktar.h>
#include <kstandarddirs.h>

#include <kio/netaccess.h>

using namespace Kross::Api;

namespace Kross { namespace Api {

    /// @internal
    class ScriptGUIClientPrivate
    {
        public:
            /**
             * The \a KXMLGUIClient that is parent of the \a ScriptGUIClient
             * instance.
             */
            KXMLGUIClient* guiclient;

            /**
             * The optional parent TQWidget widget.
             */
            TQWidget* parent;

            /**
             * Map of \a ScriptActionCollection instances the \a ScriptGUIClient
             * is attached to.
             */
            TQMap<TQString, ScriptActionCollection*> collections;
    };

}}

ScriptGUIClient::ScriptGUIClient(KXMLGUIClient* guiclient, TQWidget* parent)
    : TQObject( parent )
    , KXMLGUIClient( guiclient )
    , d( new ScriptGUIClientPrivate() ) // initialize d-pointer class
{
    krossdebug( TQString("ScriptGUIClient::ScriptGUIClient() Ctor") );

    d->guiclient = guiclient;
    d->parent = parent;

    setInstance( ScriptGUIClient::instance() );

    // action to execute a scriptfile.
    new KAction(i18n("Execute Script File..."), 0, 0, this, TQT_SLOT(executeScriptFile()), actionCollection(), "executescriptfile");

    // acion to show the ScriptManagerGUI dialog.
    new KAction(i18n("Scripts Manager..."), 0, 0, this, TQT_SLOT(showScriptManager()), actionCollection(), "configurescripts");

    // The predefined ScriptActionCollection's this ScriptGUIClient provides.
    d->collections.replace("installedscripts",
        new ScriptActionCollection(i18n("Scripts"), actionCollection(), "installedscripts") );
    d->collections.replace("loadedscripts",
        new ScriptActionCollection(i18n("Loaded"), actionCollection(), "loadedscripts") );
    d->collections.replace("executedscripts",
        new ScriptActionCollection(i18n("History"), actionCollection(), "executedscripts") );

    reloadInstalledScripts();
}

ScriptGUIClient::~ScriptGUIClient()
{
    krossdebug( TQString("ScriptGUIClient::~ScriptGUIClient() Dtor") );
    for(TQMap<TQString, ScriptActionCollection*>::Iterator it = d->collections.begin(); it != d->collections.end(); ++it)
        delete it.data();
    delete d;
}

bool ScriptGUIClient::hasActionCollection(const TQString& name)
{
    return d->collections.contains(name);
}

ScriptActionCollection* ScriptGUIClient::getActionCollection(const TQString& name)
{
    return d->collections[name];
}

TQMap<TQString, ScriptActionCollection*> ScriptGUIClient::getActionCollections()
{
    return d->collections;
}

void ScriptGUIClient::addActionCollection(const TQString& name, ScriptActionCollection* collection)
{
    removeActionCollection(name);
    d->collections.replace(name, collection);
}

bool ScriptGUIClient::removeActionCollection(const TQString& name)
{
    if(d->collections.contains(name)) {
        ScriptActionCollection* c = d->collections[name];
        d->collections.remove(name);
        delete c;
        return true;
    }
    return false;
}

void ScriptGUIClient::reloadInstalledScripts()
{
    ScriptActionCollection* installedcollection = d->collections["installedscripts"];
    if(installedcollection)
        installedcollection->clear();

    TQCString partname = d->guiclient->instance()->instanceName();
    TQStringList files = TDEGlobal::dirs()->findAllResources("data", partname + "/scripts/*/*.rc");
    //files.sort();
    for(TQStringList::iterator it = files.begin(); it != files.end(); ++it)
        loadScriptConfigFile(*it);
}

bool ScriptGUIClient::installScriptPackage(const TQString& scriptpackagefile)
{
    krossdebug( TQString("Install script package: %1").arg(scriptpackagefile) );
    KTar archive( scriptpackagefile );
    if(! archive.open(IO_ReadOnly)) {
        KMessageBox::sorry(0, i18n("Could not read the package \"%1\".").arg(scriptpackagefile));
        return false;
    }

    TQCString partname = d->guiclient->instance()->instanceName();
    TQString destination = TDEGlobal::dirs()->saveLocation("data", partname + "/scripts/", true);
    //TQString destination = TDEGlobal::dirs()->saveLocation("appdata", "scripts", true);
    if(destination.isNull()) {
        krosswarning("ScriptGUIClient::installScriptPackage() Failed to determinate location where the scriptpackage should be installed to!");
        return false;
    }

    TQString packagename = TQFileInfo(scriptpackagefile).baseName();
    destination += packagename; // add the packagename to the name of the destination-directory.

    if( TQDir(destination).exists() ) {
        if( KMessageBox::warningContinueCancel(0,
            i18n("A script package with the name \"%1\" already exists. Replace this package?" ).arg(packagename),
            i18n("Replace")) != KMessageBox::Continue )
                return false;

        if(! TDEIO::NetAccess::del(destination, 0) ) {
            KMessageBox::sorry(0, i18n("Could not uninstall this script package. You may not have sufficient permissions to delete the folder \"%1\".").arg(destination));
            return false;
        }
    }

    krossdebug( TQString("Copy script-package to destination directory: %1").arg(destination) );
    const KArchiveDirectory* archivedir = archive.directory();
    archivedir->copyTo(destination, true);

    reloadInstalledScripts();
    return true;
}

bool ScriptGUIClient::uninstallScriptPackage(const TQString& scriptpackagepath)
{
    if(! TDEIO::NetAccess::del(scriptpackagepath, 0) ) {
        KMessageBox::sorry(0, i18n("Could not uninstall this script package. You may not have sufficient permissions to delete the folder \"%1\".").arg(scriptpackagepath));
        return false;
    }
    reloadInstalledScripts();
    return true;
}

bool ScriptGUIClient::loadScriptConfigFile(const TQString& scriptconfigfile)
{
    krossdebug( TQString("ScriptGUIClient::loadScriptConfig file=%1").arg(scriptconfigfile) );

    TQDomDocument domdoc;
    TQFile file(scriptconfigfile);
    if(! file.open(IO_ReadOnly)) {
        krosswarning( TQString("ScriptGUIClient::loadScriptConfig(): Failed to read scriptconfigfile: %1").arg(scriptconfigfile) );
        return false;
    }
    bool ok = domdoc.setContent(&file);
    file.close();
    if(! ok) {
        krosswarning( TQString("ScriptGUIClient::loadScriptConfig(): Failed to parse scriptconfigfile: %1").arg(scriptconfigfile) );
        return false;
    }

    return loadScriptConfigDocument(scriptconfigfile, domdoc);
}

bool ScriptGUIClient::loadScriptConfigDocument(const TQString& scriptconfigfile, const TQDomDocument &document)
{
    ScriptActionCollection* installedcollection = d->collections["installedscripts"];
    TQDomNodeList nodelist = document.elementsByTagName("ScriptAction");
    uint nodelistcount = nodelist.count();
    for(uint i = 0; i < nodelistcount; i++) {
        ScriptAction::Ptr action = new ScriptAction(scriptconfigfile, nodelist.item(i).toElement());

        if(installedcollection) {
            ScriptAction::Ptr otheraction = installedcollection->action( action->name() );
            if(otheraction) {
                // There exists already an action with the same name. Use the versionnumber
                // to see if one of them is newer and if that's the case display only
                // the newer aka those with the highest version.
                if(action->version() < otheraction->version() && action->version() >= 0) {
                    // Just don't do anything with the above created action. The
                    // shared pointer will take care of freeing the instance.
                    continue;
                }
                else if(action->version() > otheraction->version() && otheraction->version() >= 0) {
                    // The previously added scriptaction isn't up-to-date any
                    // longer. Remove it from the list of installed scripts.
                    otheraction->finalize();
                    installedcollection->detach(otheraction);
                    //otheraction->detachAll() //FIXME: why it crashes with detachAll() ?
                }
                else {
                    // else just print a warning and fall through (so, install the action
                    // and don't care any longer of the duplicated name)...
                    krosswarning( TQString("Kross::Api::ScriptGUIClient::loadScriptConfigDocument: There exists already a scriptaction with name \"%1\". Added anyway...").arg(action->name()) );
                }
            }
            installedcollection->attach( action );
        }

        connect(action.data(), TQT_SIGNAL( failed(const TQString&, const TQString&) ),
                this, TQT_SLOT( executionFailed(const TQString&, const TQString&) ));
        connect(action.data(), TQT_SIGNAL( success() ),
                this, TQT_SLOT( successfullyExecuted() ));
        connect(action.data(), TQT_SIGNAL( activated(const Kross::Api::ScriptAction*) ), TQT_SIGNAL( executionStarted(const Kross::Api::ScriptAction*)));
    }
    emit collectionChanged(installedcollection);
    return true;
}

void ScriptGUIClient::setXMLFile(const TQString& file, bool merge, bool setXMLDoc)
{
    KXMLGUIClient::setXMLFile(file, merge, setXMLDoc);
}

void ScriptGUIClient::setDOMDocument(const TQDomDocument &document, bool merge)
{
    ScriptActionCollection* installedcollection = d->collections["installedscripts"];
    if(! merge && installedcollection)
        installedcollection->clear();

    KXMLGUIClient::setDOMDocument(document, merge);
    loadScriptConfigDocument(xmlFile(), document);
}

void ScriptGUIClient::successfullyExecuted()
{
    const ScriptAction* action = dynamic_cast< const ScriptAction* >( TQObject::sender() );
    if(action) {
        emit executionFinished(action);
        ScriptActionCollection* executedcollection = d->collections["executedscripts"];
        if(executedcollection) {
            ScriptAction* actionptr = const_cast< ScriptAction* >( action );
            executedcollection->detach(actionptr);
            executedcollection->attach(actionptr);
            emit collectionChanged(executedcollection);
        }
    }
}

void ScriptGUIClient::executionFailed(const TQString& errormessage, const TQString& tracedetails)
{
    const ScriptAction* action = dynamic_cast< const ScriptAction* >( TQObject::sender() );
    if(action)
        emit executionFinished(action);
    if(tracedetails.isEmpty())
        KMessageBox::error(0, errormessage);
    else
        KMessageBox::detailedError(0, errormessage, tracedetails);
}

KURL ScriptGUIClient::openScriptFile(const TQString& caption)
{
    TQStringList mimetypes;
    TQMap<TQString, InterpreterInfo*> infos = Manager::scriptManager()->getInterpreterInfos();
    for(TQMap<TQString, InterpreterInfo*>::Iterator it = infos.begin(); it != infos.end(); ++it)
        mimetypes.append( it.data()->getMimeTypes().join(" ").stripWhiteSpace() );

    KFileDialog* filedialog = new KFileDialog(
        TQString(), // startdir
        mimetypes.join(" "), // filter
        0, // parent widget
        "ScriptGUIClientFileDialog", // name
        true // modal
    );
    if(! caption.isNull())
        filedialog->setCaption(caption);
    if( filedialog->exec() )
        return filedialog->selectedURL();
    return KURL();
}

bool ScriptGUIClient::loadScriptFile()
{
    KURL url = openScriptFile( i18n("Load Script File") );
    if(url.isValid()) {
        ScriptActionCollection* loadedcollection = d->collections["loadedscripts"];
        if(loadedcollection) {
            ScriptAction::Ptr action = new ScriptAction( url.path() );
            connect(action.data(), TQT_SIGNAL( failed(const TQString&, const TQString&) ),
                    this, TQT_SLOT( executionFailed(const TQString&, const TQString&) ));
            connect(action.data(), TQT_SIGNAL( success() ),
                    this, TQT_SLOT( successfullyExecuted() ));
            connect(action.data(), TQT_SIGNAL( activated(const Kross::Api::ScriptAction*) ), TQT_SIGNAL( executionStarted(const Kross::Api::ScriptAction*)));

            loadedcollection->detach(action);
            loadedcollection->attach(action);
            return true;
        }
    }
    return false;
}

bool ScriptGUIClient::executeScriptFile()
{
    KURL url = openScriptFile( i18n("Execute Script File") );
    if(url.isValid())
        return executeScriptFile( url.path() );
    return false;
}

bool ScriptGUIClient::executeScriptFile(const TQString& file)
{
    krossdebug( TQString("Kross::Api::ScriptGUIClient::executeScriptFile() file='%1'").arg(file) );

    ScriptAction::Ptr action = new ScriptAction(file);
    return executeScriptAction(action);
}

bool ScriptGUIClient::executeScriptAction(ScriptAction::Ptr action)
{
    connect(action.data(), TQT_SIGNAL( failed(const TQString&, const TQString&) ),
            this, TQT_SLOT( executionFailed(const TQString&, const TQString&) ));
    connect(action.data(), TQT_SIGNAL( success() ),
            this, TQT_SLOT( successfullyExecuted() ));
    connect(action.data(), TQT_SIGNAL( activated(const Kross::Api::ScriptAction*) ), TQT_SIGNAL( executionStarted(const Kross::Api::ScriptAction*)));
    action->activate();
    bool ok = action->hadException();
    action->finalize(); // execution is done.
    return ok;
}

void ScriptGUIClient::showScriptManager()
{
    KDialogBase* dialog = new KDialogBase(d->parent, "", true, i18n("Scripts Manager"), KDialogBase::Close);
    WdgScriptsManager* wsm = new WdgScriptsManager(this, dialog);
    dialog->setMainWidget(wsm);
    dialog->resize( TQSize(360, 320).expandedTo(dialog->minimumSizeHint()) );
    dialog->show();
}

#include "scriptguiclient.moc"