summaryrefslogtreecommitdiffstats
path: root/sigmodr/SigmodrUI.cpp
blob: 88939ca59b5cabf6c873cb9e7aace0ee3ca88ca6 (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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/*
 * Copyright 2008-2009 Ben Boeckel <MathStuf@gmail.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 3 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// Header include
#include "SigmodrUI.h"

// Sigmodr includes
#include "SigmodrPreferences.h"
#include "SigmodrPreferencesWidget.h"

// Sigmodr tree includes
#include <sigmodr/tree/TreeWidget.h>

// Sigmodr widget includes
#include <sigmodr/widgets/ObjectUI.h>

// Sigmod includes
#include <sigmod/Game.h>
#include <sigmod/Rules.h>

// KDE includes
#include <KAction>
#include <KActionCollection>
#include <KConfigDialog>
#include <KCmdLineArgs>
#include <KFileDialog>
#include <KIcon>
#include <KLocalizedString>
#include <KMenu>
#include <KMenuBar>
#include <KMessageBox>
#include <KRecentFilesAction>
#include <KShortcutsDialog>
#include <KStandardAction>
#include <KStandardDirs>
#include <KStatusBar>
#include <KTemporaryFile>
#include <KToolBar>
#include <KUrl>
#include <KXMLGUIFactory>
#include <KIO/NetAccess>
#include <KNS/Engine>

// Qt includes
#include <QtCore/QString>
#include <QtCore/QUrl>
#include <QtGui/QCloseEvent>
#include <QtGui/QDragEnterEvent>
#include <QtGui/QDropEvent>

using namespace Sigmod;
using namespace Sigmodr::Widgets;
using namespace Sigmodr::Tree;
using namespace Sigmodr;

SigmodrUI::SigmodrUI(QWidget* parent) :
        KXmlGuiWindow(parent)
{
    setupUi(this);
    setupActions();
    setAcceptDrops(true);
    buttonApply->setIcon(KIcon("dialog-ok-apply"));
    buttonReset->setIcon(KIcon("edit-undo"));
    buttonValidate->setIcon(KIcon("script-error"));
    boxButtons->setEnabled(false);
    buttonValidate->setEnabled(false);
    splitter->setSizes(QList<int>() << SigmodrPreferences::treeWidth() << SigmodrPreferences::panelWidth());
    connect(buttonApply, SIGNAL(clicked()), this, SLOT(update()));
    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
    if (args && args->count())
    {
        for(int i = 0; i < args->count(); ++i)
            openGame(args->url(i));
        args->clear();
    }
    else if (SigmodrPreferences::reloadOnStart())
    {
        QStringList urls = SigmodrPreferences::openFiles();
        foreach (const QString& url, urls)
            openGame(KUrl(url));
    }
    setAutoSaveSettings("MainWindow", true);
}

SigmodrUI::~SigmodrUI()
{
    closeAllGames(true);
    SigmodrPreferences::self()->writeConfig();
    KGlobal::config()->sync();
}

void SigmodrUI::dragEnterEvent(QDragEnterEvent* event)
{
    const QMimeData* data = event->mimeData();
    if (data->hasFormat("application/x-sigmod+xml") || data->hasFormat("text/uri-list"))
        event->acceptProposedAction();
}

void SigmodrUI::dropEvent(QDropEvent* event)
{
    const QMimeData* data = event->mimeData();
    bool loaded = false;
    event->setDropAction(Qt::CopyAction);
    if (data->hasFormat("application/x-sigmod+xml"))
    {
        QDomDocument xml;
        QString error;
        int line;
        int column;
        if (xml.setContent(data->data("application/x-sigmod+xml"), &error, &line, &column))
        {
            if (xml.doctype().name() == "Game")
            {
                treeSigmod->addGame(new Game(xml.documentElement()));
                loaded = true;
            }
            else
                KMessageBox::error(this, QString("The file is not a Sigmod. The doctype was reported to be %1").arg(xml.doctype().name()), "Invalid Sigmod");
        }
        else
            KMessageBox::error(this, QString("%1 at line %2, column %3").arg(error).arg(line).arg(column), "XML Error");
    }
    else if (data->hasFormat("text/uri-list"))
    {
        QList<QUrl> urls = data->urls();
        foreach (const QUrl& url, urls)
            loaded = openGame(url);
    }
    if (loaded)
        event->acceptProposedAction();
}

void SigmodrUI::update()
{
    treeSigmod->update(treeSigmod->currentIndex());
}

void SigmodrUI::closeEvent(QCloseEvent* event)
{
    KRecentFilesAction *recent = qobject_cast<KRecentFilesAction*>(actionCollection()->action(KStandardAction::name(KStandardAction::OpenRecent)));
    recent->saveEntries(KGlobal::config()->group("Recent Files"));
    if (closeAllGames())
        event->accept();
    else
        event->ignore();
}

void SigmodrUI::resizeEvent(QResizeEvent* event)
{
    event->accept();
    on_splitter_splitterMoved();
}

void SigmodrUI::setChangedTitle(const bool changed)
{
    setCaption(treeSigmod->description(m_editedIndex), changed);
}

void SigmodrUI::setDirty(const bool dirty)
{
    setDirty(dirty, m_editedIndex);
    setChangedTitle(dirty);
    actionCollection()->action("file_save")->setEnabled(dirty);
}

void SigmodrUI::setDirty(const bool dirty, const QModelIndex& index)
{
    treeSigmod->setDirty(treeSigmod->game(index), dirty);
}

void SigmodrUI::newGame()
{
    Game* game = new Game;
    treeSigmod->addGame(game);
}

void SigmodrUI::openGame()
{
    KUrl::List urls = KFileDialog::getOpenUrls(KUrl("kfiledialog:///sigmod"), "*.smod|Sigmod files", this);
    foreach (const KUrl& url, urls)
    {
        if (!url.isEmpty())
            openGame(url);
    }
}

bool SigmodrUI::openGame(const KUrl& url)
{
    bool opened = false;
    if (treeSigmod->isOpen(url))
    {
        KMessageBox::error(this, "File is already opened", "Sigmod error");
        return false;
    }
    if (url.isValid())
    {
        if (url.isLocalFile())
            opened = openGame(url.path());
        else
        {
            QString temp;
            if (KIO::NetAccess::download(url, temp, this))
            {
                opened = openGame(temp, true);
                KIO::NetAccess::removeTempFile(temp);
            }
            else
                KMessageBox::error(this, KIO::NetAccess::lastErrorString(), "KIO Error");
        }
    }
    else
        KMessageBox::error(this, "The URL is not valid", "Malformed URL");
    if (opened)
        qobject_cast<KRecentFilesAction*>(actionCollection()->action(KStandardAction::name(KStandardAction::OpenRecent)))->addUrl(url);
    return opened;
}

bool SigmodrUI::openGame(const QString& path, const bool isRemote)
{
    QFile file(path);
    if (file.open(QIODevice::ReadOnly))
    {
        QDomDocument xml;
        QString error;
        int line;
        int column;
        if (xml.setContent(&file, &error, &line, &column))
        {
            if (xml.doctype().name() == "Game")
            {
                treeSigmod->addGame(new Game(xml.documentElement()), isRemote ? KUrl() : KUrl(path));
                return true;
            }
            else
                KMessageBox::error(this, QString("The file is not a Sigmod. The doctype was reported to be %1").arg(xml.doctype().name()), "Invalid Sigmod");
        }
        else
            KMessageBox::error(this, QString("%1 at line %2, column %3").arg(error).arg(line).arg(column), "XML Error");
        file.close();
    }
    else
        KMessageBox::error(this, file.errorString(), "File Error");
    return false;
}

void SigmodrUI::saveGame()
{
    saveGame(treeSigmod->game(treeSigmod->currentIndex()));
}

void SigmodrUI::saveGame(const Game* game)
{
    const KUrl url = treeSigmod->url(game);
    if (url.isEmpty())
        saveAsGame(game);
    else
        saveGame(game, url);
}

bool SigmodrUI::saveGame(const Game* game, const KUrl& url)
{
    if (game)
    {
        if (url.isLocalFile())
        {
            QFile file(url.path());
            if (file.open(QIODevice::WriteOnly))
            {
                file.write(Object::xml(game).toByteArray());
                treeSigmod->setDirty(game, false);
                file.close();
                return true;
            }
            else
                KMessageBox::error(this, "Error saving the Sigmod!", "Save error");
        }
        else
        {
            KTemporaryFile temp;
            if (temp.open())
            {
                temp.write(Object::xml(game).toByteArray());
                if (KIO::NetAccess::upload(temp.fileName(), url, this))
                {
                    treeSigmod->setDirty(game, false);
                    return true;
                }
                else
                    KMessageBox::error(this, KIO::NetAccess::lastErrorString(), "KIO Error");
            }
            else
                KMessageBox::error(this, "Error saving the Sigmod!", "Save error");
            temp.close();
        }
    }
    return false;
}

void SigmodrUI::saveAsGame()
{
    saveAsGame(treeSigmod->game(treeSigmod->currentIndex()));
}

void SigmodrUI::saveAsGame(const Game* game)
{
    if (game)
    {
        KUrl url = KFileDialog::getSaveUrl(KUrl("kfiledialog:///sigmod"), "*.smod|Sigmod files", this, "Open Sigmod");
        if (!url.isEmpty())
        {
            if (saveGame(game, url))
                treeSigmod->setUrl(game, url);
        }
    }
}

void SigmodrUI::downloadGame()
{
    KNS::Engine engine(this);
    if (engine.init("sigmod.knsrc"))
        engine.downloadDialogModal();
}

void SigmodrUI::uploadGame()
{
    uploadGame(treeSigmod->game(treeSigmod->currentIndex()));
}

void SigmodrUI::uploadGame(const Game* game)
{
    KUrl url = treeSigmod->url(game);
    if (url == KUrl())
    {
        KMessageBox::error(this, "The Sigmod has not been saved!", "Upload error");
        return;
    }
    if (!url.isLocalFile())
    {
        KMessageBox::error(this, "The Sigmod is not local!", "Upload error");
        return;
    }
    KNS::Engine engine(this);
    if (engine.init("sigmod.knsrc"))
    {
        if (!engine.uploadDialogModal(url.path()))
            KMessageBox::error(this, "An error occurred attempting to upload!", "Upload error");
    }
}

bool SigmodrUI::closeWidget()
{
    bool closed = true;
    if (formPanel->widget() && boxButtons->isEnabled())
    {
        switch (KMessageBox::questionYesNoCancel(this, "You have unsaved changes, would you like to save them?", QString("Unsaved %1").arg(qobject_cast<ObjectUI*>(formPanel->widget())->object()->className())))
        {
            case KMessageBox::Yes:
                qobject_cast<ObjectUI*>(formPanel->widget())->apply();
                break;
            case KMessageBox::No:
                qobject_cast<ObjectUI*>(formPanel->widget())->discard();
                break;
            case KMessageBox::Cancel:
                closed = false;
                break;
        }
    }
    if (closed)
    {
        delete formPanel->takeWidget();
        m_editedIndex = QModelIndex();
        formPanel->setWidget(NULL);
        boxButtons->setEnabled(false);
        buttonValidate->setEnabled(false);
    }
    return closed;
}

void SigmodrUI::closeGame()
{
    closeGame(treeSigmod->game(treeSigmod->currentIndex()));
    setChangedTitle(treeSigmod->dirty());
}

bool SigmodrUI::closeGame(const Game* game, const bool force)
{
    if (game)
    {
        const ObjectUI* widget = qobject_cast<ObjectUI*>(formPanel->widget());
        if (widget && (game == widget->object()->game()) && !closeWidget())
            return false;
        if (treeSigmod->dirty(game))
        {
            int result;
            if (force)
                result = KMessageBox::questionYesNo(this, "You have unsaved changes, would you like to save them?", "Unsaved Sigmod");
            else
                result = KMessageBox::questionYesNoCancel(this, "You have unsaved changes, would you like to save them?", "Unsaved Sigmod");
            switch (result)
            {
                case KMessageBox::Yes:
                    saveGame(game);
                case KMessageBox::No:
                    break;
                case KMessageBox::Cancel:
                    return false;
            }
        }
        treeSigmod->deleteGame(game);
    }
    return true;
}

bool SigmodrUI::closeAllGames(const bool force)
{
    QList<const Game*> games = treeSigmod->openedGames();
    if (games.size())
        SigmodrPreferences::setOpenFiles(treeSigmod->urls());
    for (int i = 0; i < games.size(); )
    {
        if (closeGame(games[i], force))
            games.removeAt(i);
        else
            ++i;
    }
    if (!games.size() || force)
        close();
    return !games.size();
}

void SigmodrUI::copyObject()
{
//     m_clipboard = treeSigmod->copy(treeSigmod->currentIndex());
}

void SigmodrUI::pasteObject()
{
//     treeSigmod->paste(treeSigmod->currentIndex(), m_clipboard);
}

void SigmodrUI::preferences()
{
    if (KConfigDialog::showDialog("sigmodr-prefs"))
        return;
    KConfigDialog* dialog = new KConfigDialog(this, "sigmodr-prefs", SigmodrPreferences::self());
    SigmodrPreferencesWidget* widget = new SigmodrPreferencesWidget;
    dialog->addPage(widget, i18nc("General settings tab", "General"), "configure");
    connect(dialog, SIGNAL(okClicked()), widget, SLOT(save()));
    dialog->exec();
}

void SigmodrUI::toggleMenubar()
{
    if (menuBar()->isVisible())
        menuBar()->hide();
    else
        menuBar()->show();
}

void SigmodrUI::on_splitter_splitterMoved()
{
    SigmodrPreferences::setTreeWidth(splitter->sizes()[0]);
    SigmodrPreferences::setPanelWidth(splitter->sizes()[1]);
}

void SigmodrUI::on_treeSigmod_clicked(const QModelIndex& index)
{
    if (!(treeSigmod->model()->flags(index) & Qt::ItemIsEnabled))
        return;
    switch (index.column())
    {
        case 1:
        {
            ObjectUI* editor = treeSigmod->editorWidget(index);
            if (editor && closeWidget())
            {
                connect(editor, SIGNAL(changed(bool)), boxButtons, SLOT(setEnabled(bool)));
                connect(editor, SIGNAL(saved()), this, SLOT(setDirty()));
                // TODO: Better way?
                connect(editor, SIGNAL(saved()), treeSigmod, SLOT(doItemsLayout()));
                connect(buttonApply, SIGNAL(clicked()), editor, SLOT(apply()));
                connect(buttonReset, SIGNAL(clicked()), editor, SLOT(discard()));
                connect(buttonValidate, SIGNAL(clicked()), editor, SLOT(validate()));
                m_editedIndex = index;
                setChangedTitle(treeSigmod->dirty(treeSigmod->game(index)));
                buttonValidate->setEnabled(true);
                formPanel->setWidget(editor);
                formPanel->show();
            }
            break;
        }
        case 2:
            if ((m_editedIndex.internalId() != index.internalId()) || closeWidget())
            {
                if (treeSigmod->model()->removeRow(index.row(), index.parent()))
                    setDirty(true, index);
            }
            break;
        case 3:
            if (treeSigmod->model()->insertRow(treeSigmod->model()->rowCount(index), index))
                setDirty(true, index);
            break;
        default:
            break;
    }
}

void SigmodrUI::setupActions()
{
    KStandardAction::openNew(this, SLOT(newGame()), actionCollection());
    KStandardAction::open(this, SLOT(openGame()), actionCollection());
    KRecentFilesAction* recent = KStandardAction::openRecent(this, SLOT(openGame(const KUrl&)), actionCollection());
    recent->loadEntries(KGlobal::config()->group("Recent Files"));
    KStandardAction::save(this, SLOT(saveGame()), actionCollection());
    KStandardAction::saveAs(this, SLOT(saveAsGame()), actionCollection());
    KStandardAction::close(this, SLOT(closeGame()), actionCollection());
    KStandardAction::quit(this, SLOT(closeAllGames()), actionCollection());
    KStandardAction::cut(actionCollection());
    KStandardAction::copy(actionCollection());
    KStandardAction::paste(actionCollection());
    KAction* download = actionCollection()->addAction("download_sigmod");
    download->setText(i18n("Download"));
    download->setIcon(KIcon("arrow-down-double"));
    download->setShortcut(Qt::CTRL + Qt::Key_D);
    connect(download, SIGNAL(triggered()), this, SLOT(downloadGame()));
    KAction* upload = actionCollection()->addAction("upload_sigmod");
    upload->setText(i18n("Upload"));
    upload->setIcon(KIcon("arrow-up-double"));
    upload->setShortcut(Qt::CTRL + Qt::Key_U);
    upload->setEnabled(false);
    connect(upload, SIGNAL(triggered()), this, SLOT(uploadGame()));
    KStandardAction::showMenubar(this, SLOT(toggleMenubar()), actionCollection());
    KStandardAction::configureToolbars(this, SLOT(configureToolbars()), actionCollection());
    createStandardStatusBarAction();
    setStandardToolBarMenuEnabled(true);
    KStandardAction::keyBindings(guiFactory(), SLOT(configureShortcuts()), actionCollection());
    KStandardAction::preferences(this, SLOT(preferences()), actionCollection());
    setHelpMenuEnabled(true);
    createGUI();
}