mainwindow.cpp 24.8 KB
Newer Older
Mehrdad Momeny's avatar
Mehrdad Momeny committed
1 2 3
/*
    This file is part of Blogilo, A KDE Blogging Client

4 5
    Copyright (C) 2008-2010 Mehrdad Momeny <mehrdad.momeny@gmail.com>
    Copyright (C) 2008-2010 Golnaz Nilieh <g382nilieh@gmail.com>
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
6
    Copyright (C) 2013 Laurent Montel <montel@kde.org>
Mehrdad Momeny's avatar
Mehrdad Momeny committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

    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) version 3 or any later version
    accepted by the membership of KDE e.V. (or its successor approved
    by the membership of KDE e.V.), which shall act as a proxy
    defined in Section 14 of version 3 of the license.

    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/
*/
24 25 26 27 28 29 30 31 32 33 34 35

#include "mainwindow.h"
#include "global.h"
#include "dbman.h"
#include "toolbox.h"
#include "postentry.h"
#include "addeditblog.h"
#include "backend.h"
#include "bilbomedia.h"
#include "settings.h"
#include "bilboblog.h"
#include "blogsettings.h"
36
#include "poststabwidget.h"
Laurent Montel's avatar
Laurent Montel committed
37
#include "uploadmediadialog.h"
38 39
#include "configuredialog.h"
#include "storageservice/storageservicemanagersettingsjob.h"
40 41 42 43 44

#include "ui_advancedsettingsbase.h"
#include "ui_settingsbase.h"
#include "ui_editorsettingsbase.h"

45 46 47
#include "pimcommon/storageservice/storageservicemanager.h"
#include "pimcommon/storageservice/storageservicejobconfig.h"
#include "pimcommon/storageservice/storageserviceabstract.h"
48
#include "pimcommon/storageservice/storageserviceprogressmanager.h"
49

50 51
#include "libkdepim/progresswidget/progressdialog.h"
#include "libkdepim/progresswidget/statusbarprogresswidget.h"
52
#include "libkdepim/progresswidget/progressstatusbarwidget.h"
53

54
#include <ktabwidget.h>
55
#include <KStatusNotifierItem>
56
#include <qstatusbar.h>
57 58
#include <KToggleAction>
#include <kactioncollection.h>
59
#include <KActionMenu>
Laurent Montel's avatar
Port++  
Laurent Montel committed
60
#include <QAction>
61
#include <kconfigdialog.h>
Laurent Montel's avatar
Laurent Montel committed
62
#include <qdebug.h>
63
#include <kmessagebox.h>
Laurent Montel's avatar
Laurent Montel committed
64
#include <KLocalizedString>
Laurent Montel's avatar
Laurent Montel committed
65 66 67
#include <KSelectAction>
#include <kimagefilepreview.h>
#include <KToolInvocation>
Laurent Montel's avatar
Port++  
Laurent Montel committed
68
#include <QMenu>
Laurent Montel's avatar
KUrl--  
Laurent Montel committed
69
#include <QUrl>
Laurent Montel's avatar
Laurent Montel committed
70

Laurent Montel's avatar
Laurent Montel committed
71 72
#include <QDockWidget>
#include <QProgressBar>
Mehrdad Momeny's avatar
Mehrdad Momeny committed
73
#include <QTimer>
74
#include <QKeyEvent>
75 76 77 78

#define TIMEOUT 5000

MainWindow::MainWindow()
Laurent Montel's avatar
Laurent Montel committed
79 80 81 82 83 84 85
    : KXmlGuiWindow(),
      activePost(0),
      systemTray(0),
      previousActivePostIndex(-1),
      busyNumber(0),
      progress(0),
      mCurrentBlogId(__currentBlogId)
86
{
Laurent Montel's avatar
Laurent Montel committed
87
    setWindowTitle(i18n("Blogilo"));
88
    initStorageService();
89

90
    tabPosts = new PostsTabWidget(this);
Laurent Montel's avatar
Laurent Montel committed
91
    setCentralWidget(tabPosts);
Laurent Montel's avatar
Laurent Montel committed
92 93 94 95
    connect(tabPosts, &PostsTabWidget::createNewPost, this, &MainWindow::slotCreateNewPost);
    connect(tabPosts, &PostsTabWidget::closeTabClicked, this, &MainWindow::slotCloseTabClicked);
    connect(tabPosts, &PostsTabWidget::tabCloseRequested, this, &MainWindow::slotRemovePostEntry);
    connect(tabPosts, &PostsTabWidget::tabRemoveAllExclude, this, &MainWindow::slotRemoveAllExclude);
96

Laurent Montel's avatar
Laurent Montel committed
97 98 99 100 101
    toolbox = new Toolbox(this);
    toolboxDock = new QDockWidget(i18n("Toolbox"), this);
    toolboxDock->setAllowedAreas(Qt::RightDockWidgetArea | Qt::LeftDockWidgetArea);
    toolboxDock->setFeatures(QDockWidget::AllDockWidgetFeatures);
    toolboxDock->setWidget(toolbox);
Laurent Montel's avatar
Laurent Montel committed
102

Laurent Montel's avatar
Laurent Montel committed
103 104
    toolboxDock->setObjectName(QLatin1String("dock_toolbox"));
    toolbox->setObjectName(QLatin1String("toolbox"));
Laurent Montel's avatar
Laurent Montel committed
105

Laurent Montel's avatar
Laurent Montel committed
106
    this->addDockWidget(Qt::RightDockWidgetArea, toolboxDock);
107 108 109

    // then, setup our actions
    setupActions();
110
    setupStatusBar();
111 112 113 114 115 116 117 118

    // a call to KXmlGuiWindow::setupGUI() populates the GUI
    // with actions, using KXMLGUI.
    // It also applies the saved mainwindow settings, if any, and ask the
    // mainwindow to automatically save settings if changed: window size,
    // toolbar position, icon size, etc.
    setupGUI();

Laurent Montel's avatar
Laurent Montel committed
119 120
    toolbox->setVisible(Settings::showToolboxOnStart());
    actionCollection()->action(QLatin1String("toggle_toolbox"))->setChecked(Settings::showToolboxOnStart());
121 122 123

    setupSystemTray();

Laurent Montel's avatar
Laurent Montel committed
124
    connect(tabPosts, SIGNAL(currentChanged(int)), this, SLOT(slotActivePostChanged(int)));
Laurent Montel's avatar
Laurent Montel committed
125 126 127
    connect(toolbox, &Toolbox::sigEntrySelected, this, &MainWindow::slotNewPostOpened);
    connect(toolbox, &Toolbox::sigError, this, &MainWindow::slotError);
    connect(toolbox, &Toolbox::sigBusy, this, &MainWindow::slotBusy);
128

Laurent Montel's avatar
Laurent Montel committed
129
    QList<BilboBlog *> blogList = DBMan::self()->blogList().values();
Laurent Montel's avatar
Laurent Montel committed
130
    const int count = blogList.count();
Laurent Montel's avatar
Laurent Montel committed
131 132 133 134 135
    for (int i = 0; i < count; ++i) {
        QAction *act = new QAction(blogList.at(i)->title(), blogs);
        act->setCheckable(true);
        act->setData(blogList.at(i)->id());
        blogs->addAction(act);
136
    }
Laurent Montel's avatar
Laurent Montel committed
137 138
    connect(blogs, static_cast<void (KSelectAction::*)(QAction *)>(&KSelectAction::triggered), this, &MainWindow::currentBlogChanged);
    QTimer::singleShot(0, this, SLOT(loadTempPosts()));
139 140 141 142
}

MainWindow::~MainWindow()
{
143 144
}

145 146
void MainWindow::setupStatusBar()
{
Laurent Montel's avatar
Laurent Montel committed
147 148
    KPIM::ProgressStatusBarWidget *progressStatusBarWidget = new KPIM::ProgressStatusBarWidget(statusBar(), this, PimCommon::StorageServiceProgressManager::progressTypeValue());
    statusBar()->addPermanentWidget(progressStatusBarWidget->littleProgress(), 0);
149 150 151
    statusBar()->show();
}

152 153 154 155 156 157 158
void MainWindow::initStorageService()
{
    StorageServiceManagerSettingsJob *settingsJob = new StorageServiceManagerSettingsJob(this);
    PimCommon::StorageServiceJobConfig *configJob = PimCommon::StorageServiceJobConfig::self();
    configJob->registerConfigIf(settingsJob);

    mStorageManager = new PimCommon::StorageServiceManager(this);
Laurent Montel's avatar
Laurent Montel committed
159 160 161 162
    connect(mStorageManager, &PimCommon::StorageServiceManager::uploadFileDone, this, &MainWindow::slotUploadFileDone);
    connect(mStorageManager, &PimCommon::StorageServiceManager::shareLinkDone, this, &MainWindow::slotUploadFileDone);
    connect(mStorageManager, &PimCommon::StorageServiceManager::uploadFileFailed, this, &MainWindow::slotUploadFileFailed);
    connect(mStorageManager, &PimCommon::StorageServiceManager::actionFailed, this, &MainWindow::slotActionFailed);
163 164 165 166 167 168 169 170 171 172 173 174 175
}

void MainWindow::slotUploadFileDone(const QString &serviceName, const QString &link)
{
    Q_UNUSED(serviceName);
    KMessageBox::information(this, i18n("File uploaded. You can access to it at this url %1", link), i18n("Upload File"));
}

void MainWindow::slotUploadFileFailed(const QString &serviceName, const QString &filename)
{
    Q_UNUSED(serviceName);
    Q_UNUSED(filename);
    KMessageBox::error(this, i18n("Error during upload."), i18n("Upload File"));
176 177
}

Laurent Montel's avatar
Laurent Montel committed
178 179 180 181 182
void MainWindow::slotActionFailed(const QString &serviceName, const QString &error)
{
    KMessageBox::error(this, i18n("%1 return an error '%2'", serviceName, error), i18n("Error"));
}

183 184 185 186 187 188 189 190
void MainWindow::slotCloseTabClicked()
{
    const int currentIndex = tabPosts->currentIndex();
    if (currentIndex != -1) {
        slotRemovePostEntry(currentIndex);
    }
}

191
void MainWindow::closeEvent(QCloseEvent *event)
192
{
193
    writeConfigs();
Laurent Montel's avatar
Laurent Montel committed
194 195 196
    if (!DBMan::self()->clearTempEntries()) {
        qDebug() << "Could not erase temp_post table: " << DBMan::self()->lastErrorText();
    }
Laurent Montel's avatar
Laurent Montel committed
197
    const int count = tabPosts->count();
198
    if (count > 0) {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
199
        toolbox->getFieldsValue(activePost->currentPost());
Laurent Montel's avatar
Laurent Montel committed
200 201
        for (int i = 0; i < count; ++i) {
            PostEntry *pst = qobject_cast<PostEntry *>(tabPosts->widget(i));
Mehrdad Momeny's avatar
Mehrdad Momeny committed
202 203
            DBMan::self()->saveTempEntry(*pst->currentPost(), pst->currentPostBlogId());
        }
204
    }
205
    event->accept();
206 207 208 209
}

void MainWindow::setupActions()
{
Laurent Montel's avatar
Laurent Montel committed
210
    KStandardAction::quit(qApp, SLOT(quit()), actionCollection());
211

Laurent Montel's avatar
Laurent Montel committed
212
    KStandardAction::preferences(this, SLOT(optionsPreferences()), actionCollection());
213 214

    // custom menu and menu item
Laurent Montel's avatar
Laurent Montel committed
215 216 217
    QAction *actNewPost = new QAction(QIcon::fromTheme(QLatin1String("document-new")), i18n("New Post"), this);
    actionCollection()->addAction(QLatin1String("new_post"), actNewPost);
    actionCollection()->setDefaultShortcut(actNewPost, QKeySequence(Qt::CTRL + Qt::Key_N));
Laurent Montel's avatar
Laurent Montel committed
218
    connect(actNewPost, &QAction::triggered, this, &MainWindow::slotCreateNewPost);
219

Laurent Montel's avatar
Laurent Montel committed
220 221
    QAction *actAddBlog = new QAction(QIcon::fromTheme(QLatin1String("list-add")), i18n("Add Blog..."), this);
    actionCollection()->addAction(QLatin1String("add_blog"), actAddBlog);
Laurent Montel's avatar
Laurent Montel committed
222
    connect(actAddBlog, &QAction::triggered, this, &MainWindow::addBlog);
223

Laurent Montel's avatar
Laurent Montel committed
224 225
    QAction *actPublish = new QAction(QIcon::fromTheme(QLatin1String("arrow-up")), i18n("Submit..."), this);
    actionCollection()->addAction(QLatin1String("publish_post"), actPublish);
Laurent Montel's avatar
Laurent Montel committed
226
    connect(actPublish, &QAction::triggered, this, &MainWindow::slotPublishPost);
227

Laurent Montel's avatar
Laurent Montel committed
228 229
    QAction *actUpload = new QAction(QIcon::fromTheme(QLatin1String("upload-media")), i18n("Upload Media..."), this);
    actionCollection()->addAction(QLatin1String("upload_media"), actUpload);
Laurent Montel's avatar
Laurent Montel committed
230
    connect(actUpload, &QAction::triggered, this, &MainWindow::uploadMediaObject);
231

Laurent Montel's avatar
Laurent Montel committed
232 233 234
    QAction *actSaveLocally = new QAction(QIcon::fromTheme(QLatin1String("document-save")), i18n("Save Locally"), this);
    actionCollection()->addAction(QLatin1String("save_locally"), actSaveLocally);
    actionCollection()->setDefaultShortcut(actSaveLocally, QKeySequence(Qt::CTRL + Qt::Key_S));
Laurent Montel's avatar
Laurent Montel committed
235
    connect(actSaveLocally, &QAction::triggered, this, &MainWindow::slotSavePostLocally);
236

Laurent Montel's avatar
Laurent Montel committed
237 238 239 240 241 242 243
    KToggleAction *actToggleToolboxVisible = new KToggleAction(i18n("Show Toolbox"), this);
    actionCollection()->addAction(QLatin1String("toggle_toolbox"), actToggleToolboxVisible);
    actionCollection()->setDefaultShortcut(actToggleToolboxVisible, QKeySequence(Qt::CTRL + Qt::Key_T));
    connect(actToggleToolboxVisible, SIGNAL(toggled(bool)),
            this, SLOT(slotToggleToolboxVisible(bool)));
    connect(toolboxDock, SIGNAL(visibilityChanged(bool)),
            this, SLOT(slotToolboxVisibilityChanged(bool)));
244

Laurent Montel's avatar
Laurent Montel committed
245 246
    blogs = new KSelectAction(this);
    actionCollection()->addAction(QLatin1String("blogs_list"), blogs);
247

Laurent Montel's avatar
Port++  
Laurent Montel committed
248
    QAction *actOpenBlog = new QAction(QIcon::fromTheme(QLatin1String("applications-internet")), i18n("Open in browser"), this);
Laurent Montel's avatar
Laurent Montel committed
249
    actionCollection()->addAction(QLatin1String("open_blog_in_browser"), actOpenBlog);
250
    actOpenBlog->setToolTip(i18n("Open current blog in browser"));
Laurent Montel's avatar
Laurent Montel committed
251
    connect(actOpenBlog, &QAction::triggered, this, &MainWindow::slotOpenCurrentBlogInBrowser);
252

Laurent Montel's avatar
Laurent Montel committed
253 254
    actionCollection()->addAction(QLatin1String("upload_file"), mStorageManager->menuUploadServices(this));
    actionCollection()->addAction(QLatin1String("download_file"), mStorageManager->menuDownloadServices(this));
Laurent Montel's avatar
Laurent Montel committed
255
    mStorageManager->setDefaultUploadFolder(Settings::self()->downloadDirectory());
256 257 258 259
}

void MainWindow::loadTempPosts()
{
Laurent Montel's avatar
Laurent Montel committed
260
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
261
    QMap<BilboPost *, int> tempList = DBMan::self()->listTempPosts();
Laurent Montel's avatar
Laurent Montel committed
262
    const int count = tempList.count();
Laurent Montel's avatar
Laurent Montel committed
263 264 265 266
    if (count > 0) {
        QMap<BilboPost *, int>::ConstIterator it = tempList.constBegin();
        QMap<BilboPost *, int>::ConstIterator endIt = tempList.constEnd();
        for (; it != endIt; ++it) {
267 268 269
            createPostEntry(it.value(), (*it.key()));
        }
    } else {
270
        slotCreateNewPost();
271 272 273
    }
//     activePost = qobject_cast<PostEntry*>( tabPosts->currentWidget() );
    previousActivePostIndex = 0;
Laurent Montel's avatar
Laurent Montel committed
274 275 276
    if (activePost) {
        setCurrentBlog(activePost->currentPostBlogId());
    }
277 278
}

Laurent Montel's avatar
Laurent Montel committed
279
void MainWindow::setCurrentBlog(int blog_id)
280
{
Laurent Montel's avatar
Laurent Montel committed
281
    qDebug() << blog_id;
282
    if (blog_id == -1) {
Laurent Montel's avatar
Laurent Montel committed
283 284
        blogs->setCurrentItem(-1);
        toolbox->setCurrentBlogId(blog_id);
285 286 287
//         actionCollection()->action("publish_post")->setEnabled( false );
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
288
    const int count = blogs->items().count();
Laurent Montel's avatar
Laurent Montel committed
289 290 291 292
    for (int i = 0; i < count; ++i) {
        if (blogs->action(i)->data().toInt() == blog_id) {
            blogs->setCurrentItem(i);
            currentBlogChanged(blogs->action(i));
293 294 295 296 297
            break;
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
298
void MainWindow::currentBlogChanged(QAction *act)
299
{
Laurent Montel's avatar
Laurent Montel committed
300 301
    if (act) {
        if (mCurrentBlogId == act->data().toInt()) {
302
            return;
Laurent Montel's avatar
Laurent Montel committed
303
        }
304 305
        mCurrentBlogId = act->data().toInt();
//         __currentBlogId = mCurrentBlogId;
Laurent Montel's avatar
Laurent Montel committed
306
        if (activePost) {
307
//             actionCollection()->action("publish_post")->setEnabled( true );
Laurent Montel's avatar
Laurent Montel committed
308
            activePost->setCurrentPostBlogId(mCurrentBlogId);
309 310 311
        } else {
//             actionCollection()->action("publish_post")->setEnabled( false );
        }
Laurent Montel's avatar
Laurent Montel committed
312
        blogs->setToolTip(DBMan::self()->blogList().value(mCurrentBlogId)->blogUrl());
313 314
    } else {
        mCurrentBlogId = -1;
Laurent Montel's avatar
Laurent Montel committed
315 316 317
        if (activePost) {
            activePost->setCurrentPostBlogId(mCurrentBlogId);
        }
318
    }
Laurent Montel's avatar
Laurent Montel committed
319
    toolbox->setCurrentBlogId(mCurrentBlogId);
320 321
}

322
void MainWindow::slotCreateNewPost()
323
{
Laurent Montel's avatar
Laurent Montel committed
324
    qDebug();
325

Laurent Montel's avatar
Laurent Montel committed
326 327 328 329 330
    tabPosts->setCurrentWidget(createPostEntry(mCurrentBlogId, BilboPost()));
    if (mCurrentBlogId == -1) {
        if (!blogs->items().isEmpty()) {
            blogs->setCurrentItem(0);
            currentBlogChanged(blogs->action(0));
331 332
        }
    }
Laurent Montel's avatar
Laurent Montel committed
333
    if (this->isVisible() == false) {
334 335 336 337 338 339 340 341 342 343 344
        this->show();
    }
}

void MainWindow::optionsPreferences()
{
    // The preference dialog is derived from prefs_base.ui
    //
    // compare the names of the widgets in the .ui file
    // to the names of the variables in the .kcfg file
    //avoid having 2 dialogs shown
Laurent Montel's avatar
Laurent Montel committed
345
    if (KConfigDialog::showDialog(QLatin1String("settings")))  {
346 347
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
348 349 350 351 352
    ConfigureDialog *dialog = new ConfigureDialog(mStorageManager, this, QLatin1String("settings"), Settings::self());
    connect(dialog, SIGNAL(blogAdded(BilboBlog)),
            this, SLOT(slotBlogAdded(BilboBlog)));
    connect(dialog, SIGNAL(blogEdited(BilboBlog)),
            this, SLOT(slotBlogEdited(BilboBlog)));
Laurent Montel's avatar
Laurent Montel committed
353 354 355 356 357
    connect(dialog, &ConfigureDialog::blogRemoved, this, &MainWindow::slotBlogRemoved);
    connect(dialog, &ConfigureDialog::settingsChanged, this, &MainWindow::settingsChanged);
    connect(dialog, &ConfigureDialog::settingsChanged, this, &MainWindow::slotSettingsChanged);
    connect(dialog, &ConfigureDialog::dialogDestroyed, this, &MainWindow::slotDialogDestroyed);
    connect(dialog, &ConfigureDialog::settingsChanged, this, &MainWindow::slotSettingsChanged);
358 359 360 361 362 363
    dialog->show();
}

void MainWindow::slotSettingsChanged()
{
    setupSystemTray();
Laurent Montel's avatar
Laurent Montel committed
364
    mStorageManager->setDefaultUploadFolder(Settings::self()->downloadDirectory());
365 366
}

Laurent Montel's avatar
Laurent Montel committed
367
void MainWindow::slotDialogDestroyed(QObject *win)
368
{
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
369 370
    const QSize size = qobject_cast<QWidget *>(win)->size();
    const QString name = win->objectName();
371
    if (name == QLatin1String("settings")) {
Laurent Montel's avatar
Laurent Montel committed
372
        Settings::setConfigWindowSize(size);
373 374 375 376 377
    }
}

void MainWindow::addBlog()
{
Laurent Montel's avatar
Laurent Montel committed
378 379 380 381 382
    AddEditBlog *addEditBlogWindow = new AddEditBlog(-1, this);
    addEditBlogWindow->setWindowModality(Qt::ApplicationModal);
    addEditBlogWindow->setAttribute(Qt::WA_DeleteOnClose);
    connect(addEditBlogWindow, SIGNAL(sigBlogAdded(BilboBlog)),
            this, SLOT(slotBlogAdded(BilboBlog)));
383 384 385
    addEditBlogWindow->show();
}

Laurent Montel's avatar
Laurent Montel committed
386
void MainWindow::slotBlogAdded(const BilboBlog &blog)
387
{
Laurent Montel's avatar
Laurent Montel committed
388 389 390 391 392 393
    QAction *act = new QAction(blog.title(), blogs);
    act->setCheckable(true);
    act->setData(blog.id());
    blogs->addAction(act);
    blogs->setCurrentAction(act);
    currentBlogChanged(act);
394
    toolbox->slotReloadCategoryList();
Laurent Montel's avatar
Laurent Montel committed
395
    toolbox->slotUpdateEntries(20);
396 397
}

Laurent Montel's avatar
Laurent Montel committed
398
void MainWindow::slotBlogEdited(const BilboBlog &blog)
399
{
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
400
    const int count = blogs->actions().count();
Laurent Montel's avatar
Laurent Montel committed
401 402 403
    for (int i = 0; i < count; ++i) {
        if (blogs->action(i)->data().toInt() == blog.id()) {
            blogs->action(i)->setText(blog.title());
404 405 406 407 408
            break;
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
409
void MainWindow::slotBlogRemoved(int blog_id)
410
{
Laurent Montel's avatar
Laurent Montel committed
411
    const int count = blogs->actions().count();
Laurent Montel's avatar
Laurent Montel committed
412 413 414 415 416
    for (int i = 0; i < count; ++i) {
        if (blogs->action(i)->data().toInt() == blog_id) {
            if (blogs->currentItem() == i) {
                blogs->setCurrentItem(i - 1);
                currentBlogChanged(blogs->action(i - 1));
417
            }
Laurent Montel's avatar
Laurent Montel committed
418 419
            blogs->removeAction(blogs->action(i));
            if (blogs->currentItem() == -1) {
420
                toolbox->clearFields();
Laurent Montel's avatar
Laurent Montel committed
421
            }
422 423 424 425 426 427 428
            break;
        }
    }
}

void MainWindow::setupSystemTray()
{
Laurent Montel's avatar
Laurent Montel committed
429 430 431
    if (Settings::enableSysTrayIcon()) {
        if (!systemTray) {
            systemTray = new KStatusNotifierItem(this);
Laurent Montel's avatar
Laurent Montel committed
432
            systemTray->setIconByName(QLatin1String("blogilo"));
Laurent Montel's avatar
Laurent Montel committed
433 434
            systemTray->setToolTip(QLatin1String("blogilo"), i18n("Blogilo"), i18n("A KDE Blogging Client"));
            systemTray->contextMenu()->addAction(actionCollection()->action(QLatin1String("new_post")));
435 436
            systemTray->setCategory(KStatusNotifierItem::ApplicationStatus);
            systemTray->setStatus(KStatusNotifierItem::Active);
437
        }
Laurent Montel's avatar
Laurent Montel committed
438
    } else if (systemTray) {
439 440 441 442 443
        systemTray->deleteLater();
        systemTray = 0;
    }
}

Laurent Montel's avatar
Laurent Montel committed
444
void MainWindow::slotPostTitleChanged(const QString &title)
445
{
Laurent Montel's avatar
Laurent Montel committed
446
//     qDebug();
Laurent Montel's avatar
Laurent Montel committed
447
    tabPosts->setTabText(tabPosts->currentIndex(), title);
448 449
}

Laurent Montel's avatar
Laurent Montel committed
450
void MainWindow::slotToggleToolboxVisible(bool isVisible)
451
{
Laurent Montel's avatar
Laurent Montel committed
452
    toolboxDock->setVisible(isVisible);
453 454 455 456
}

void MainWindow::slotToolboxVisibilityChanged(bool)
{
Laurent Montel's avatar
Laurent Montel committed
457
    actionCollection()->action(QLatin1String("toggle_toolbox"))->setChecked(toolboxDock->isVisibleTo(this));
458 459
}

Laurent Montel's avatar
Laurent Montel committed
460
void MainWindow::slotActivePostChanged(int index)
461
{
Laurent Montel's avatar
Laurent Montel committed
462
    qDebug() << "new post index: " << index << "\tPrev Index: " << previousActivePostIndex;
463

Laurent Montel's avatar
Laurent Montel committed
464 465
    activePost = qobject_cast<PostEntry *>(tabPosts->widget(index));
    PostEntry *prevActivePost = qobject_cast<PostEntry *>(tabPosts->widget(previousActivePostIndex));
466 467 468
    int activePostBlogId = -1;
    int prevPostBlogId = -1;

Laurent Montel's avatar
Laurent Montel committed
469
    if ((prevActivePost != 0) && (index != previousActivePostIndex)) {
470
        prevPostBlogId = prevActivePost->currentPostBlogId();
Laurent Montel's avatar
Laurent Montel committed
471 472
        toolbox->getFieldsValue(prevActivePost->currentPost());
        prevActivePost->setCurrentPostBlogId(mCurrentBlogId);
473 474
    }

Laurent Montel's avatar
Laurent Montel committed
475
    if (index >= 0) {
476
        activePostBlogId = activePost->currentPostBlogId();
Laurent Montel's avatar
Laurent Montel committed
477 478
        if (activePostBlogId != -1 && activePostBlogId != prevPostBlogId) {
            setCurrentBlog(activePostBlogId);
479
        }
Laurent Montel's avatar
Laurent Montel committed
480
        toolbox->setFieldsValue(activePost->currentPost());
481
    } else {
Laurent Montel's avatar
Laurent Montel committed
482
        qCritical() << "ActivePost is NULL! tabPosts Current index is: " << tabPosts->currentIndex() ;
483 484 485 486
    }
    previousActivePostIndex = index;
}

487
void MainWindow::slotPublishPost()
488
{
Laurent Montel's avatar
Laurent Montel committed
489
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
490 491
    if (mCurrentBlogId == -1) {
        KMessageBox::sorry(this, i18n("You have to select a blog to publish this post to."));
492 493
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
494 495
    if (!activePost || tabPosts->currentIndex() == -1) {
        KMessageBox::sorry(this, i18n("There is no open post to submit."));
496 497
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
498 499
    toolbox->getFieldsValue(activePost->currentPost());
    activePost->submitPost(mCurrentBlogId, *activePost->currentPost());
500 501
}

502 503
void MainWindow::slotRemoveAllExclude(int pos)
{
Laurent Montel's avatar
Laurent Montel committed
504
    for (int i = tabPosts->count() - 1; i >= 0; --i) {
505 506 507
        if (i == pos) {
            continue;
        }
Laurent Montel's avatar
Laurent Montel committed
508 509 510
        PostEntry *widget = qobject_cast<PostEntry *>(tabPosts->widget(i));
        if (!widget) {
            if (activePost) {
511
                widget = activePost;
Laurent Montel's avatar
Laurent Montel committed
512
            } else {
513
                return;
Laurent Montel's avatar
Laurent Montel committed
514
            }
515
        }
Laurent Montel's avatar
Laurent Montel committed
516
        DBMan::self()->removeTempEntry(*widget->currentPost());
517 518 519
        tabPosts->removePage(widget);
        widget->close();
    }
Laurent Montel's avatar
Laurent Montel committed
520
    if (tabPosts->count() < 1) {
521 522 523 524 525 526
        activePost = 0;
        toolbox->resetFields();
//         actionCollection()->action("publish_post")->setEnabled( false );
    }
}

Laurent Montel's avatar
Laurent Montel committed
527
void MainWindow::slotRemovePostEntry(int pos)
528
{
Laurent Montel's avatar
Laurent Montel committed
529
    qDebug();
530

Laurent Montel's avatar
Laurent Montel committed
531 532 533 534
    PostEntry *widget = qobject_cast<PostEntry *>(tabPosts->widget(pos));

    if (!widget) {
        if (activePost) {
535
            widget = activePost;
Laurent Montel's avatar
Laurent Montel committed
536
        } else {
537
            return;
Laurent Montel's avatar
Laurent Montel committed
538
        }
539
    }
Laurent Montel's avatar
Laurent Montel committed
540
    DBMan::self()->removeTempEntry(*widget->currentPost());
541 542 543
    tabPosts->removePage(widget);
    widget->close();

Laurent Montel's avatar
Laurent Montel committed
544
    if (tabPosts->count() < 1) {
545 546 547 548 549 550
        activePost = 0;
        toolbox->resetFields();
//         actionCollection()->action("publish_post")->setEnabled( false );
    }
}

Laurent Montel's avatar
Laurent Montel committed
551
void MainWindow::slotNewPostOpened(BilboPost &newPost, int blog_id)
552
{
Laurent Montel's avatar
Laurent Montel committed
553
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
554 555
    QWidget *w = createPostEntry(blog_id, newPost);
    tabPosts->setCurrentWidget(w);
556 557
}

558
void MainWindow::slotSavePostLocally()
559
{
Laurent Montel's avatar
Laurent Montel committed
560
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
561
    if (activePost && (tabPosts->count() > 0)) {
562
        toolbox->getFieldsValue(activePost->currentPost());
563 564 565 566 567
        activePost->saveLocally();
        toolbox->reloadLocalPosts();
    }
}

Laurent Montel's avatar
Laurent Montel committed
568
void MainWindow::slotError(const QString &errorMessage)
569
{
Laurent Montel's avatar
Laurent Montel committed
570
    qDebug() << "Error message: " << errorMessage;
Laurent Montel's avatar
Laurent Montel committed
571
    KMessageBox::detailedError(this, i18n("An error occurred in the last transaction."), errorMessage);
572 573 574 575 576 577
    statusBar()->clearMessage();
    slotBusy(false);
}

void MainWindow::writeConfigs()
{
Laurent Montel's avatar
Laurent Montel committed
578
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    if (toolboxDock->isVisible()) {
        Settings::setShowToolboxOnStart(true);
    } else {
        Settings::setShowToolboxOnStart(false);
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::CTRL) {
        switch (event->key()) {
        case  Qt::Key_1:
            toolbox->setCurrentPage(0);
            break;
        case Qt::Key_2:
            toolbox->setCurrentPage(1);
            break;
        case Qt::Key_3:
            toolbox->setCurrentPage(2);
            break;
        case Qt::Key_4:
            toolbox->setCurrentPage(3);
            break;
        case Qt::Key_5:
            toolbox->setCurrentPage(4);
            break;
        case Qt::Key_W:
            slotRemovePostEntry(tabPosts->currentIndex());
            break;
        default:
            KXmlGuiWindow::keyPressEvent(event);
            break;
611 612 613 614
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
615
void MainWindow::postManipulationDone(bool isError, const QString &customMessage)
616
{
Laurent Montel's avatar
Laurent Montel committed
617
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
618
    if (isError) {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
619
        KMessageBox::detailedError(this, i18n("Submitting post failed"), customMessage);
620
    } else {
Laurent Montel's avatar
Laurent Montel committed
621 622 623 624 625 626 627 628
        PostEntry *entry = qobject_cast<PostEntry *>(sender());
        if (entry) {
            if (KMessageBox::questionYesNo(this, i18n("%1\nDo you want to keep the post open?", customMessage),
                                           QString(), KStandardGuiItem::yes(), KStandardGuiItem::no(), QLatin1String("KeepPostOpen")) == KMessageBox::No) {
                slotRemovePostEntry(tabPosts->indexOf(entry));
            } else {
                toolbox->setFieldsValue(entry->currentPost());
            }
629
        }
Laurent Montel's avatar
Laurent Montel committed
630
        toolbox->slotLoadEntriesFromDB(mCurrentBlogId);
631 632 633 634 635 636 637
    }
    this->unsetCursor();
    toolbox->unsetCursor();
}

void MainWindow::slotBusy(bool isBusy)
{
Laurent Montel's avatar
Laurent Montel committed
638 639
    qDebug() << "isBusy=" << isBusy << "\tbusyNumber=" << busyNumber;
    if (isBusy) {
640
        this->setCursor(Qt::BusyCursor);
Laurent Montel's avatar
Laurent Montel committed
641
        toolbox->setCursor(Qt::BusyCursor);
642
        ++busyNumber;
Laurent Montel's avatar
Laurent Montel committed
643
        if (!progress) {
644
            progress = new QProgressBar(statusBar());
Laurent Montel's avatar
Laurent Montel committed
645 646
            progress->setMinimum(0);
            progress->setMaximum(0);
647 648 649 650 651
            progress->setFixedSize(250, 17);
            statusBar()->addPermanentWidget(progress);
        }
    } else {
        --busyNumber;
Laurent Montel's avatar
Laurent Montel committed
652
        if (busyNumber < 1) {
653 654
            this->unsetCursor();
            toolbox->unsetCursor();
Laurent Montel's avatar
Laurent Montel committed
655
            if (progress) {
656 657 658 659 660 661 662 663 664
                statusBar()->removeWidget(progress);
                progress->deleteLater();
                progress = 0;
            }
//             busyNumber = 0;
        }
    }
}

Laurent Montel's avatar
Laurent Montel committed
665
QWidget *MainWindow::createPostEntry(int blog_id, const BilboPost &post)
666
{
Laurent Montel's avatar
Laurent Montel committed
667
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
668 669
    PostEntry *temp = new PostEntry(this);
    temp->setAttribute(Qt::WA_DeleteOnClose);
670
    temp->setCurrentPost(post);
Laurent Montel's avatar
Laurent Montel committed
671
    temp->setCurrentPostBlogId(blog_id);
672

Laurent Montel's avatar
Laurent Montel committed
673 674 675 676
    connect(temp, SIGNAL(postTitleChanged(QString)),
            this, SLOT(slotPostTitleChanged(QString)));
    connect(temp, SIGNAL(postPublishingDone(bool,QString)),
            this, SLOT(postManipulationDone(bool,QString)));
Laurent Montel's avatar
Laurent Montel committed
677
    connect(this, &MainWindow::settingsChanged, temp, &PostEntry::settingsChanged);
Laurent Montel's avatar
Laurent Montel committed
678 679
    connect(temp, SIGNAL(showStatusMessage(QString,bool)),
            this, SLOT(slotShowStatusMessage(QString,bool)));
680

Laurent Montel's avatar
Laurent Montel committed
681
    connect(temp, &PostEntry::sigBusy, this, &MainWindow::slotBusy);
682

Laurent Montel's avatar
Laurent Montel committed
683
    tabPosts->addTab(temp, post.title());
684 685 686 687 688 689 690 691 692 693 694
    return temp;
}

void MainWindow::slotShowStatusMessage(const QString &message, bool isPermanent)
{
    statusBar()->showMessage(message, (isPermanent ? 0 : TIMEOUT));
}

void MainWindow::uploadMediaObject()
{
    UploadMediaDialog *uploadDlg = new UploadMediaDialog(this);
Laurent Montel's avatar
Laurent Montel committed
695
    connect(uploadDlg, &UploadMediaDialog::sigBusy, this, &MainWindow::slotBusy);
Laurent Montel's avatar
Laurent Montel committed
696 697 698 699 700
    if (mCurrentBlogId == -1) {
        uploadDlg->init(0);
    } else {
        uploadDlg->init(DBMan::self()->blog(mCurrentBlogId));
    }
701 702
}

703 704
void MainWindow::slotOpenCurrentBlogInBrowser()
{
Mehrdad Momeny's avatar
Mehrdad Momeny committed
705
    if (mCurrentBlogId > -1) {
Laurent Montel's avatar
KUrl--  
Laurent Montel committed
706
        QUrl url(DBMan::self()->blog(mCurrentBlogId)->blogUrl());
Laurent Montel's avatar
Laurent Montel committed
707
        if (url.isValid()) {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
708
            KToolInvocation::invokeBrowser(url.url());
Laurent Montel's avatar
Laurent Montel committed
709
        } else {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
710
            KMessageBox::sorry(this, i18n("Cannot find current blog URL."));
Laurent Montel's avatar
Laurent Montel committed
711
        }
712 713
    }
    ///TODO
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
714
    ///else show a message to the user saying that a blog should be selected before.
715 716
}