mainwindow.cpp 24.9 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 24

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

#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"
37
#include "poststabwidget.h"
Laurent Montel's avatar
Laurent Montel committed
38
#include "uploadmediadialog.h"
39 40
#include "configuredialog.h"
#include "storageservice/storageservicemanagersettingsjob.h"
41 42 43 44 45

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

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

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

55
#include <ktabwidget.h>
56
#include <KStatusNotifierItem>
57 58 59
#include <kstatusbar.h>
#include <KToggleAction>
#include <kactioncollection.h>
60
#include <KActionMenu>
Laurent Montel's avatar
Port++  
Laurent Montel committed
61
#include <QAction>
62
#include <kconfigdialog.h>
Laurent Montel's avatar
Laurent Montel committed
63
#include <qdebug.h>
64
#include <kmessagebox.h>
65
#include <KLocale>
Laurent Montel's avatar
Laurent Montel committed
66 67 68
#include <KSelectAction>
#include <kimagefilepreview.h>
#include <KToolInvocation>
Laurent Montel's avatar
Port++  
Laurent Montel committed
69
#include <QMenu>
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
{
Mehrdad Momeny's avatar
Mehrdad Momeny committed
87
    setWindowTitle( i18n("Blogilo") );
88
    initStorageService();
89

90
    tabPosts = new PostsTabWidget(this);
91
    setCentralWidget( tabPosts );
92 93
    connect(tabPosts,SIGNAL(createNewPost()),SLOT(slotCreateNewPost()));
    connect(tabPosts,SIGNAL(closeTabClicked()),SLOT(slotCloseTabClicked()));
94 95
    connect(tabPosts,SIGNAL(tabCloseRequested(int)), this, SLOT(slotRemovePostEntry(int)));
    connect(tabPosts,SIGNAL(tabRemoveAllExclude(int)), this, SLOT(slotRemoveAllExclude(int)));
96

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 103 104 105

    toolboxDock->setObjectName( QLatin1String("dock_toolbox") );
    toolbox->setObjectName( QLatin1String("toolbox") );

106 107 108 109
    this->addDockWidget( Qt::RightDockWidgetArea, toolboxDock );

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

    // 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();

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

    setupSystemTray();

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

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

MainWindow::~MainWindow()
{
143 144
}

145 146
void MainWindow::setupStatusBar()
{
147
    KPIM::ProgressStatusBarWidget * progressStatusBarWidget = new KPIM::ProgressStatusBarWidget(statusBar(), this, PimCommon::StorageServiceProgressManager::progressTypeValue());
148
    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);
159 160 161
    connect(mStorageManager, SIGNAL(uploadFileDone(QString,QString)), this, SLOT(slotUploadFileDone(QString,QString)));
    connect(mStorageManager, SIGNAL(shareLinkDone(QString,QString)), this, SLOT(slotUploadFileDone(QString,QString)));
    connect(mStorageManager, SIGNAL(uploadFileFailed(QString,QString)), this, SLOT(slotUploadFileFailed(QString,QString)));
Laurent Montel's avatar
Laurent Montel committed
162
    connect(mStorageManager, SIGNAL(actionFailed(QString,QString)), this, SLOT(slotActionFailed(QString,QString)));
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();
194
    if ( !DBMan::self()->clearTempEntries() )
Laurent Montel's avatar
Laurent Montel committed
195
        qDebug()<<"Could not erase temp_post table: "<< DBMan::self()->lastErrorText();
Laurent Montel's avatar
Laurent Montel committed
196
    const int count = tabPosts->count();
197
    if (count > 0) {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
198 199 200 201 202
        toolbox->getFieldsValue(activePost->currentPost());
        for(int i =0; i<count; ++i) {
            PostEntry* pst = qobject_cast<PostEntry*>(tabPosts->widget(i));
            DBMan::self()->saveTempEntry(*pst->currentPost(), pst->currentPostBlogId());
        }
203
    }
204
    event->accept();
205 206 207 208
}

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

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

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

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

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

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

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

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

    blogs = new KSelectAction( this );
    actionCollection()->addAction( QLatin1String( "blogs_list" ), blogs );
246

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

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

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

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

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

318
void MainWindow::slotCreateNewPost()
319
{
Laurent Montel's avatar
Laurent Montel committed
320
    qDebug();
321 322

    tabPosts->setCurrentWidget( createPostEntry( mCurrentBlogId, BilboPost()) );
323 324
    if ( mCurrentBlogId == -1 ) {
        if ( !blogs->items().isEmpty() ) {
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
            blogs->setCurrentItem( 0 );
            currentBlogChanged( blogs->action( 0 ) );
        }
    }
    if ( this->isVisible() == false ) {
        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
341
    if ( KConfigDialog::showDialog( QLatin1String("settings") ) )  {
342 343
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
344
    ConfigureDialog *dialog = new ConfigureDialog( mStorageManager, this, QLatin1String("settings"), Settings::self() );
345
    connect( dialog, SIGNAL(blogAdded(BilboBlog)),
Laurent Montel's avatar
Laurent Montel committed
346
             this, SLOT(slotBlogAdded(BilboBlog)) );
347
    connect( dialog, SIGNAL(blogEdited(BilboBlog)),
Laurent Montel's avatar
Laurent Montel committed
348
             this, SLOT(slotBlogEdited(BilboBlog)) );
349
    connect( dialog, SIGNAL(blogRemoved(int)), this, SLOT(slotBlogRemoved(int)) );
Laurent Montel's avatar
Laurent Montel committed
350 351
    connect( dialog, SIGNAL(settingsChanged(QString)), this, SIGNAL(settingsChanged()) );
    connect( dialog, SIGNAL(settingsChanged(QString)), this, SLOT(slotSettingsChanged()) );
352
    connect( dialog, SIGNAL(dialogDestroyed(QObject*)), this, SLOT(slotDialogDestroyed(QObject*)));
Laurent Montel's avatar
Laurent Montel committed
353
    connect( dialog, SIGNAL(settingsChanged()), this, SLOT(slotSettingsChanged()));
354 355 356 357 358 359
    dialog->show();
}

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

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

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

void MainWindow::slotBlogAdded( const BilboBlog &blog )
{
    QAction *act = new QAction( blog.title(), blogs );
    act->setCheckable( true );
    act->setData( blog.id() );
    blogs->addAction( act );
    blogs->setCurrentAction( act );
    currentBlogChanged( act );
390 391
    toolbox->slotReloadCategoryList();
    toolbox->slotUpdateEntries( 20 );
392 393 394 395
}

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

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

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

439
void MainWindow::slotPostTitleChanged( const QString& title )
440
{
Laurent Montel's avatar
Laurent Montel committed
441
//     qDebug();
442 443 444
    tabPosts->setTabText( tabPosts->currentIndex(), title );
}

445
void MainWindow::slotToggleToolboxVisible( bool isVisible )
446 447 448 449 450 451 452 453 454
{
    toolboxDock->setVisible( isVisible );
}

void MainWindow::slotToolboxVisibilityChanged(bool)
{
    actionCollection()->action(QLatin1String("toggle_toolbox"))->setChecked( toolboxDock->isVisibleTo(this) );
}

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

    activePost = qobject_cast<PostEntry*>( tabPosts->widget( index ) );
    PostEntry *prevActivePost = qobject_cast<PostEntry*>( tabPosts->widget( previousActivePostIndex ) );
    int activePostBlogId = -1;
    int prevPostBlogId = -1;

    if (( prevActivePost != 0 ) && ( index != previousActivePostIndex ) ) {
        prevPostBlogId = prevActivePost->currentPostBlogId();
466
        toolbox->getFieldsValue( prevActivePost->currentPost() );
467 468 469 470 471 472 473 474 475 476
        prevActivePost->setCurrentPostBlogId( mCurrentBlogId );
    }

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

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

497 498 499 500 501 502 503
void MainWindow::slotRemoveAllExclude(int pos)
{
    for(int i = tabPosts->count()-1; i >=0; --i) {
        if (i == pos) {
            continue;
        }
        PostEntry *widget = qobject_cast<PostEntry*>( tabPosts->widget( i ) );
504 505
        if ( !widget ) {
            if ( activePost )
506 507 508 509 510 511 512 513
                widget = activePost;
            else
                return;
        }
        DBMan::self()->removeTempEntry( *widget->currentPost() );
        tabPosts->removePage(widget);
        widget->close();
    }
514
    if ( tabPosts->count() < 1 ) {
515 516 517 518 519 520
        activePost = 0;
        toolbox->resetFields();
//         actionCollection()->action("publish_post")->setEnabled( false );
    }
}

521
void MainWindow::slotRemovePostEntry( int pos )
522
{
Laurent Montel's avatar
Laurent Montel committed
523
    qDebug();
524 525 526

    PostEntry *widget = qobject_cast<PostEntry*>( tabPosts->widget( pos ) );
    
527 528
    if ( !widget ) {
        if ( activePost )
529 530 531
            widget = activePost;
        else
            return;
532 533 534 535 536
    }
    DBMan::self()->removeTempEntry( *widget->currentPost() );
    tabPosts->removePage(widget);
    widget->close();

537
    if ( tabPosts->count() < 1 ) {
538 539 540 541 542 543
        activePost = 0;
        toolbox->resetFields();
//         actionCollection()->action("publish_post")->setEnabled( false );
    }
}

544
void MainWindow::slotNewPostOpened( BilboPost &newPost, int blog_id )
545
{
Laurent Montel's avatar
Laurent Montel committed
546
    qDebug();
547 548 549 550
    QWidget * w = createPostEntry( blog_id, newPost );
    tabPosts->setCurrentWidget( w );
}

551
void MainWindow::slotSavePostLocally()
552
{
Laurent Montel's avatar
Laurent Montel committed
553
    qDebug();
Laurent Montel's avatar
Laurent Montel committed
554
    if (activePost && (tabPosts->count() > 0)) {
555
        toolbox->getFieldsValue(activePost->currentPost());
556 557 558 559 560
        activePost->saveLocally();
        toolbox->reloadLocalPosts();
    }
}

561
void MainWindow::slotError( const QString & errorMessage )
562
{
Laurent Montel's avatar
Laurent Montel committed
563
    qDebug() << "Error message: " << errorMessage;
Andrew Coles's avatar
Andrew Coles committed
564
    KMessageBox::detailedError( this, i18n( "An error occurred in the last transaction." ), errorMessage );
565 566 567 568 569 570
    statusBar()->clearMessage();
    slotBusy(false);
}

void MainWindow::writeConfigs()
{
Laurent Montel's avatar
Laurent Montel committed
571
    qDebug();
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    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:
598
                slotRemovePostEntry( tabPosts->currentIndex() );
599 600 601 602 603 604 605 606 607 608
                break;
            default:
                KXmlGuiWindow::keyPressEvent( event );
                break;
        }
    }
}

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

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

QWidget* MainWindow::createPostEntry(int blog_id, const BilboPost& post)
{
Laurent Montel's avatar
Laurent Montel committed
659
    qDebug();
660 661 662 663 664
    PostEntry *temp = new PostEntry( this );
    temp->setAttribute( Qt::WA_DeleteOnClose );
    temp->setCurrentPost(post);
    temp->setCurrentPostBlogId( blog_id );

Laurent Montel's avatar
Laurent Montel committed
665 666 667 668 669 670
    connect( temp, SIGNAL(postTitleChanged(QString)),
             this, SLOT(slotPostTitleChanged(QString)) );
    connect( temp, SIGNAL(postPublishingDone(bool,QString)),
            this, SLOT(postManipulationDone(bool,QString)) );
    connect( this, SIGNAL(settingsChanged()), temp, SLOT(settingsChanged()));
    connect( temp, SIGNAL(showStatusMessage(QString,bool)),
671 672
             this, SLOT(slotShowStatusMessage(QString,bool)));

Laurent Montel's avatar
Laurent Montel committed
673
    connect( temp, SIGNAL(sigBusy(bool)), this, SLOT(slotBusy(bool)) );
674 675 676 677 678 679 680 681 682 683 684 685 686 687

    tabPosts->addTab( temp, post.title() );
    return temp;
}

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

void MainWindow::uploadMediaObject()
{
    UploadMediaDialog *uploadDlg = new UploadMediaDialog(this);
    connect(uploadDlg, SIGNAL(sigBusy(bool)), SLOT(slotBusy(bool)));
688
    if (mCurrentBlogId == -1)
689 690
        uploadDlg->init( 0 );
    else
Mehrdad Momeny's avatar
Mehrdad Momeny committed
691
        uploadDlg->init( DBMan::self()->blog(mCurrentBlogId) );
692 693
}

694 695
void MainWindow::slotOpenCurrentBlogInBrowser()
{
Mehrdad Momeny's avatar
Mehrdad Momeny committed
696
    if (mCurrentBlogId > -1) {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
697
        KUrl url( DBMan::self()->blog( mCurrentBlogId )->blogUrl() );
698
        if (url.isValid())
Mehrdad Momeny's avatar
Mehrdad Momeny committed
699 700 701
            KToolInvocation::invokeBrowser(url.url());
        else
            KMessageBox::sorry(this, i18n("Cannot find current blog URL."));
702 703
    }
    ///TODO
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
704
    ///else show a message to the user saying that a blog should be selected before.
705 706
}