mainwindow.cpp 23.2 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 41 42 43 44

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

#include <ktabwidget.h>
45
#include <KStatusNotifierItem>
46 47 48 49 50 51 52
#include <kstatusbar.h>
#include <KToggleAction>
#include <kactioncollection.h>
#include <kconfigdialog.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <KDE/KLocale>
Laurent Montel's avatar
Laurent Montel committed
53 54 55 56 57
#include <KSelectAction>
#include <kimagefilepreview.h>
#include <KToolInvocation>
#include <KMenu>

Laurent Montel's avatar
Laurent Montel committed
58 59
#include <QDockWidget>
#include <QProgressBar>
Mehrdad Momeny's avatar
Mehrdad Momeny committed
60
#include <QTimer>
61
#include <QKeyEvent>
62 63 64 65

#define TIMEOUT 5000

MainWindow::MainWindow()
Laurent Montel's avatar
Laurent Montel committed
66 67 68 69 70 71 72
    : KXmlGuiWindow(),
      activePost(0),
      systemTray(0),
      previousActivePostIndex(-1),
      busyNumber(0),
      progress(0),
      mCurrentBlogId(__currentBlogId)
73
{
Mehrdad Momeny's avatar
Mehrdad Momeny committed
74
    setWindowTitle( i18n("Blogilo") );
75

76
    tabPosts = new PostsTabWidget(this);
77
    setCentralWidget( tabPosts );
78 79
    connect(tabPosts,SIGNAL(createNewPost()),SLOT(slotCreateNewPost()));
    connect(tabPosts,SIGNAL(closeTabClicked()),SLOT(slotCloseTabClicked()));
80 81
    connect(tabPosts,SIGNAL(tabCloseRequested(int)), this, SLOT(slotRemovePostEntry(int)));
    connect(tabPosts,SIGNAL(tabRemoveAllExclude(int)), this, SLOT(slotRemoveAllExclude(int)));
82

83 84 85 86 87
    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
88 89 90 91

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

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    this->addDockWidget( Qt::RightDockWidgetArea, toolboxDock );

    // then, setup our actions
    setupActions();

    // add a status bar
    statusBar()->show();

    // 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
108
    actionCollection()->action(QLatin1String("toggle_toolbox"))->setChecked( Settings::showToolboxOnStart() );
109 110 111

    setupSystemTray();

Laurent Montel's avatar
Laurent Montel committed
112 113 114 115
    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)));
116 117

    QList<BilboBlog*> blogList = DBMan::self()->blogList().values();
Laurent Montel's avatar
Laurent Montel committed
118
    const int count = blogList.count();
119
    for(int i=0; i < count; ++i) {
Laurent Montel's avatar
Laurent Montel committed
120
        QAction *act = new QAction( blogList.at(i)->title(), blogs );
121
        act->setCheckable( true );
Laurent Montel's avatar
Laurent Montel committed
122
        act->setData( blogList.at(i)->id() );
123 124
        blogs->addAction( act );
    }
Laurent Montel's avatar
Laurent Montel committed
125 126
    connect( blogs, SIGNAL(triggered(QAction*)), this, SLOT(currentBlogChanged(QAction*)) );
    QTimer::singleShot( 0, this, SLOT(loadTempPosts()) );
127 128 129 130
}

MainWindow::~MainWindow()
{
131 132
}

133 134 135 136 137 138 139 140
void MainWindow::slotCloseTabClicked()
{
    const int currentIndex = tabPosts->currentIndex();
    if (currentIndex != -1) {
        slotRemovePostEntry(currentIndex);
    }
}

141 142
bool MainWindow::queryExit()
{
143
    writeConfigs();
144
    if ( !DBMan::self()->clearTempEntries() )
145
        kDebug()<<"Could not erase temp_post table: "<< DBMan::self()->lastErrorText();
Laurent Montel's avatar
Laurent Montel committed
146
    const int count = tabPosts->count();
147
    if (count > 0) {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
148 149 150 151 152
        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());
        }
153 154
    }
    return true;
155 156 157 158
}

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

Laurent Montel's avatar
Laurent Montel committed
161
    KStandardAction::preferences( this, SLOT(optionsPreferences()), actionCollection() );
162 163

    // custom menu and menu item
Laurent Montel's avatar
Laurent Montel committed
164
    KAction *actNewPost = new KAction( KIcon( QLatin1String("document-new") ), i18n( "New Post" ), this );
165 166
    actionCollection()->addAction( QLatin1String( "new_post" ), actNewPost );
    actNewPost->setShortcut( Qt::CTRL + Qt::Key_N );
Laurent Montel's avatar
Laurent Montel committed
167
    connect( actNewPost, SIGNAL(triggered(bool)), this, SLOT(slotCreateNewPost()) );
168

Laurent Montel's avatar
Laurent Montel committed
169
    KAction *actAddBlog = new KAction( KIcon( QLatin1String("list-add") ), i18n( "Add Blog..." ), this );
170
    actionCollection()->addAction( QLatin1String( "add_blog" ), actAddBlog );
Laurent Montel's avatar
Laurent Montel committed
171
    connect( actAddBlog, SIGNAL(triggered(bool)), this, SLOT(addBlog()) );
172

Laurent Montel's avatar
Laurent Montel committed
173
    KAction *actPublish = new KAction( KIcon( QLatin1String("arrow-up") ), i18n( "Submit..." ), this );
174
    actionCollection()->addAction( QLatin1String( "publish_post" ), actPublish );
Laurent Montel's avatar
Laurent Montel committed
175
    connect( actPublish, SIGNAL(triggered(bool)), this, SLOT(slotPublishPost()) );
176

Laurent Montel's avatar
Laurent Montel committed
177
    KAction *actUpload = new KAction( KIcon( QLatin1String("upload-media") ), i18n( "Upload Media..." ), this );
178
    actionCollection()->addAction( QLatin1String( "upload_media" ), actUpload );
Laurent Montel's avatar
Laurent Montel committed
179
    connect( actUpload, SIGNAL(triggered(bool)), this, SLOT(uploadMediaObject()) );
180

Laurent Montel's avatar
Laurent Montel committed
181
    KAction *actSaveLocally = new KAction( KIcon( QLatin1String("document-save") ), i18n( "Save Locally" ), this );
182 183
    actionCollection()->addAction( QLatin1String( "save_locally" ), actSaveLocally );
    actSaveLocally->setShortcut( Qt::CTRL + Qt::Key_S );
Laurent Montel's avatar
Laurent Montel committed
184
    connect( actSaveLocally, SIGNAL(triggered(bool)), this, SLOT(slotSavePostLocally()) );
185 186 187 188

    KToggleAction *actToggleToolboxVisible = new KToggleAction( i18n( "Show Toolbox" ), this );
    actionCollection()->addAction( QLatin1String( "toggle_toolbox" ), actToggleToolboxVisible );
    actToggleToolboxVisible->setShortcut( Qt::CTRL + Qt::Key_T );
Laurent Montel's avatar
Laurent Montel committed
189 190
    connect( actToggleToolboxVisible, SIGNAL(toggled(bool)),
             this, SLOT(slotToggleToolboxVisible(bool)) );
191
    connect( toolboxDock, SIGNAL(visibilityChanged(bool)),
Laurent Montel's avatar
Laurent Montel committed
192
             this, SLOT(slotToolboxVisibilityChanged(bool)) );
193 194 195

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

Laurent Montel's avatar
Laurent Montel committed
197
    KAction *actOpenBlog = new KAction(KIcon(QLatin1String("applications-internet")), i18n("Open in browser"), this);
198 199 200
    actionCollection()->addAction( QLatin1String("open_blog_in_browser"), actOpenBlog);
    actOpenBlog->setToolTip(i18n("Open current blog in browser"));
    connect( actOpenBlog, SIGNAL(triggered(bool)), this, SLOT(slotOpenCurrentBlogInBrowser()) );
201 202 203 204 205 206
}

void MainWindow::loadTempPosts()
{
    kDebug();
    QMap<BilboPost*, int> tempList = DBMan::self()->listTempPosts();
Laurent Montel's avatar
Laurent Montel committed
207
    const int count = tempList.count();
208
    if ( count > 0 ){
209 210 211 212 213 214
        QMap<BilboPost*, int>::ConstIterator it = tempList.constBegin();
        QMap<BilboPost*, int>::ConstIterator endIt = tempList.constEnd();
        for( ; it != endIt; ++it ) {
            createPostEntry(it.value(), (*it.key()));
        }
    } else {
215
        slotCreateNewPost();
216 217 218
    }
//     activePost = qobject_cast<PostEntry*>( tabPosts->currentWidget() );
    previousActivePostIndex = 0;
219
    if ( activePost )
220 221 222 223 224 225
        setCurrentBlog( activePost->currentPostBlogId() );
}

void MainWindow::setCurrentBlog( int blog_id )
{
    kDebug()<<blog_id;
226
    if (blog_id == -1) {
227 228 229 230 231
        blogs->setCurrentItem( -1 );
        toolbox->setCurrentBlogId( blog_id );
//         actionCollection()->action("publish_post")->setEnabled( false );
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
232
    const int count = blogs->items().count();
233
    for (int i=0; i<count; ++i) {
234
        if ( blogs->action(i)->data().toInt() == blog_id ) {
235 236 237 238 239 240 241 242 243
            blogs->setCurrentItem( i );
            currentBlogChanged( blogs->action( i ) );
            break;
        }
    }
}

void MainWindow::currentBlogChanged( QAction *act )
{
244 245
    if ( act ) {
        if ( mCurrentBlogId == act->data().toInt() )
246 247 248
            return;
        mCurrentBlogId = act->data().toInt();
//         __currentBlogId = mCurrentBlogId;
249
        if ( activePost ) {
250 251 252 253 254 255 256 257
//             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;
258
        if ( activePost )
259 260 261 262 263
            activePost->setCurrentPostBlogId( mCurrentBlogId );
    }
    toolbox->setCurrentBlogId( mCurrentBlogId );
}

264
void MainWindow::slotCreateNewPost()
265 266 267 268
{
    kDebug();

    tabPosts->setCurrentWidget( createPostEntry( mCurrentBlogId, BilboPost()) );
269 270
    if ( mCurrentBlogId == -1 ) {
        if ( !blogs->items().isEmpty() ) {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
            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
287
    if ( KConfigDialog::showDialog( QLatin1String("settings") ) )  {
288 289
        return;
    }
Laurent Montel's avatar
Laurent Montel committed
290
    KConfigDialog *dialog = new KConfigDialog( this, QLatin1String("settings"), Settings::self() );
291 292 293 294 295 296 297
    QWidget *generalSettingsDlg = new QWidget;
    generalSettingsDlg->setAttribute( Qt::WA_DeleteOnClose );
    Ui::SettingsBase ui_prefs_base;
    Ui::EditorSettingsBase ui_editorsettings_base;
    ui_prefs_base.setupUi( generalSettingsDlg );
    BlogSettings *blogSettingsDlg = new BlogSettings;
    blogSettingsDlg->setAttribute( Qt::WA_DeleteOnClose );
Laurent Montel's avatar
Laurent Montel committed
298 299 300 301
    connect( blogSettingsDlg, SIGNAL(blogAdded(BilboBlog)),
             this, SLOT(slotBlogAdded(BilboBlog)) );
    connect( blogSettingsDlg, SIGNAL(blogEdited(BilboBlog)),
             this, SLOT(slotBlogEdited(BilboBlog)) );
302 303 304 305 306 307 308 309 310
    connect( blogSettingsDlg, SIGNAL(blogRemoved(int)), this, SLOT(slotBlogRemoved(int)) );
    QWidget *editorSettingsDlg = new QWidget;
    editorSettingsDlg->setAttribute( Qt::WA_DeleteOnClose );
    ui_editorsettings_base.setupUi( editorSettingsDlg );
    QWidget *advancedSettingsDlg = new QWidget;
    advancedSettingsDlg->setAttribute( Qt::WA_DeleteOnClose );
    Ui::AdvancedSettingsBase ui_advancedsettings_base;
    ui_advancedsettings_base.setupUi( advancedSettingsDlg );

Laurent Montel's avatar
Laurent Montel committed
311 312 313 314
    dialog->addPage( generalSettingsDlg, i18nc( "Configure Page", "General" ), QLatin1String("configure") );
    dialog->addPage( blogSettingsDlg, i18nc( "Configure Page", "Blogs" ), QLatin1String("document-properties"));
    dialog->addPage( editorSettingsDlg, i18nc( "Configure Page", "Editor" ), QLatin1String("accessories-text-editor"));
    dialog->addPage( advancedSettingsDlg, i18nc( "Configure Page", "Advanced" ), QLatin1String("applications-utilities"));
Laurent Montel's avatar
Laurent Montel committed
315 316
    connect( dialog, SIGNAL(settingsChanged(QString)), this, SIGNAL(settingsChanged()) );
    connect( dialog, SIGNAL(settingsChanged(QString)), this, SLOT(slotSettingsChanged()) );
317 318 319 320 321 322 323 324 325 326 327 328 329
    connect( dialog, SIGNAL(destroyed(QObject*)), this, SLOT(slotDialogDestroyed(QObject*)));
    dialog->setAttribute( Qt::WA_DeleteOnClose );
    dialog->resize( Settings::configWindowSize() );
    dialog->show();
}

void MainWindow::slotSettingsChanged()
{
    setupSystemTray();
}

void MainWindow::slotDialogDestroyed( QObject *win )
{
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
330 331
    const QSize size = qobject_cast<QWidget *>(win)->size();
    const QString name = win->objectName();
332
    if (name == QLatin1String("settings")) {
333 334 335 336 337 338 339 340 341
        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
342 343
    connect( addEditBlogWindow, SIGNAL(sigBlogAdded(BilboBlog)),
             this, SLOT(slotBlogAdded(BilboBlog)) );
344 345 346 347 348 349 350 351 352 353 354
    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 );
355 356
    toolbox->slotReloadCategoryList();
    toolbox->slotUpdateEntries( 20 );
357 358 359 360
}

void MainWindow::slotBlogEdited( const BilboBlog &blog )
{
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
361
    const int count = blogs->actions().count();
362
    for(int i=0; i< count; ++i){
363
        if ( blogs->action( i )->data().toInt() == blog.id() ) {
364 365 366 367 368 369 370 371
            blogs->action( i )->setText( blog.title() );
            break;
        }
    }
}

void MainWindow::slotBlogRemoved( int blog_id )
{
Laurent Montel's avatar
Laurent Montel committed
372
    const int count = blogs->actions().count();
373
    for(int i=0; i< count; ++i){
374 375
        if ( blogs->action( i )->data().toInt() == blog_id ) {
            if ( blogs->currentItem() == i ) {
376 377 378 379
                blogs->setCurrentItem( i-1 );
                currentBlogChanged( blogs->action( i-1 ) );
            }
            blogs->removeAction( blogs->action( i ) );
380
            if (blogs->currentItem() == -1)
381 382 383 384 385 386 387 388
                toolbox->clearFields();
            break;
        }
    }
}

void MainWindow::setupSystemTray()
{
389
    if ( Settings::enableSysTrayIcon()) {
390
        if ( !systemTray ) {
391
            systemTray = new KStatusNotifierItem( this );
Laurent Montel's avatar
Laurent Montel committed
392 393 394
            systemTray->setIconByName(QLatin1String("blogilo"));
            systemTray->setToolTip( QLatin1String("blogilo"), i18n("Blogilo"), i18n("A KDE Blogging Client") );
            systemTray->contextMenu()->addAction( actionCollection()->action(QLatin1String("new_post")) );
395 396
            systemTray->setCategory(KStatusNotifierItem::ApplicationStatus);
            systemTray->setStatus(KStatusNotifierItem::Active);
397
        }
398
    } else if ( systemTray ) {
399 400 401 402 403
        systemTray->deleteLater();
        systemTray = 0;
    }
}

404
void MainWindow::slotPostTitleChanged( const QString& title )
405 406 407 408 409
{
//     kDebug();
    tabPosts->setTabText( tabPosts->currentIndex(), title );
}

410
void MainWindow::slotToggleToolboxVisible( bool isVisible )
411 412 413 414 415 416 417 418 419
{
    toolboxDock->setVisible( isVisible );
}

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

420
void MainWindow::slotActivePostChanged( int index )
421 422 423 424 425 426 427 428 429 430
{
    kDebug() << "new post index: " << index << "\tPrev Index: " << previousActivePostIndex;

    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();
431
        toolbox->getFieldsValue( prevActivePost->currentPost() );
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
        prevActivePost->setCurrentPostBlogId( mCurrentBlogId );
    }

    if ( index >= 0 ) {
        activePostBlogId = activePost->currentPostBlogId();
        if ( activePostBlogId != -1 && activePostBlogId != prevPostBlogId ) {
                setCurrentBlog( activePostBlogId );
        }
        toolbox->setFieldsValue( activePost->currentPost() );
    } else {
        kError() << "ActivePost is NULL! tabPosts Current index is: " << tabPosts->currentIndex() ;
    }
    previousActivePostIndex = index;
}

447
void MainWindow::slotPublishPost()
448 449 450 451 452 453
{
    kDebug();
    if ( mCurrentBlogId == -1 ) {
        KMessageBox::sorry( this, i18n( "You have to select a blog to publish this post to." ) );
        return;
    }
454
    if ( !activePost || tabPosts->currentIndex() == -1) {
Andrew Coles's avatar
Andrew Coles committed
455
        KMessageBox::sorry( this, i18n( "There is no open post to submit." ) );
456 457
        return;
    }
458 459
    toolbox->getFieldsValue( activePost->currentPost() );
    activePost->submitPost( mCurrentBlogId, *activePost->currentPost() );
460 461
}

462 463 464 465 466 467 468
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 ) );
469 470
        if ( !widget ) {
            if ( activePost )
471 472 473 474 475 476 477 478
                widget = activePost;
            else
                return;
        }
        DBMan::self()->removeTempEntry( *widget->currentPost() );
        tabPosts->removePage(widget);
        widget->close();
    }
479
    if ( tabPosts->count() < 1 ) {
480 481 482 483 484 485
        activePost = 0;
        toolbox->resetFields();
//         actionCollection()->action("publish_post")->setEnabled( false );
    }
}

486
void MainWindow::slotRemovePostEntry( int pos )
487 488
{
    kDebug();
489 490 491

    PostEntry *widget = qobject_cast<PostEntry*>( tabPosts->widget( pos ) );
    
492 493
    if ( !widget ) {
        if ( activePost )
494 495 496
            widget = activePost;
        else
            return;
497 498 499 500 501
    }
    DBMan::self()->removeTempEntry( *widget->currentPost() );
    tabPosts->removePage(widget);
    widget->close();

502
    if ( tabPosts->count() < 1 ) {
503 504 505 506 507 508
        activePost = 0;
        toolbox->resetFields();
//         actionCollection()->action("publish_post")->setEnabled( false );
    }
}

509
void MainWindow::slotNewPostOpened( BilboPost &newPost, int blog_id )
510 511 512 513 514 515
{
    kDebug();
    QWidget * w = createPostEntry( blog_id, newPost );
    tabPosts->setCurrentWidget( w );
}

516
void MainWindow::slotSavePostLocally()
517 518
{
    kDebug();
Laurent Montel's avatar
Laurent Montel committed
519
    if (activePost && (tabPosts->count() > 0)) {
520
        toolbox->getFieldsValue(activePost->currentPost());
521 522 523 524 525
        activePost->saveLocally();
        toolbox->reloadLocalPosts();
    }
}

526
void MainWindow::slotError( const QString & errorMessage )
527 528
{
    kDebug() << "Error message: " << errorMessage;
Andrew Coles's avatar
Andrew Coles committed
529
    KMessageBox::detailedError( this, i18n( "An error occurred in the last transaction." ), errorMessage );
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 555 556 557 558 559 560 561 562
    statusBar()->clearMessage();
    slotBusy(false);
}

void MainWindow::writeConfigs()
{
    kDebug();
    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:
563
                slotRemovePostEntry( tabPosts->currentIndex() );
564 565 566 567 568 569 570 571 572 573 574
                break;
            default:
                KXmlGuiWindow::keyPressEvent( event );
                break;
        }
    }
}

void MainWindow::postManipulationDone( bool isError, const QString &customMessage )
{
    kDebug();
575
    if (isError){
Yuri Chornoivan's avatar
Yuri Chornoivan committed
576
        KMessageBox::detailedError(this, i18n("Submitting post failed"), customMessage);
577 578
    } else {
        PostEntry *entry = qobject_cast<PostEntry*>(sender());
579
        if (entry){
580
          if (KMessageBox::questionYesNo(this, i18n("%1\nDo you want to keep the post open?", customMessage),
Laurent Montel's avatar
Laurent Montel committed
581
                    QString(), KStandardGuiItem::yes(), KStandardGuiItem::no(), QLatin1String("KeepPostOpen")) == KMessageBox::No ) {
582
            slotRemovePostEntry( tabPosts->indexOf( entry ) );
583
          } else {
584
            toolbox->setFieldsValue(entry->currentPost());
585
          }
586
        }
587
        toolbox->slotLoadEntriesFromDB( mCurrentBlogId );
588 589 590 591 592 593 594 595
    }
    this->unsetCursor();
    toolbox->unsetCursor();
}

void MainWindow::slotBusy(bool isBusy)
{
    kDebug()<<"isBusy="<<isBusy<<"\tbusyNumber="<<busyNumber;
596
    if (isBusy){
597 598 599
        this->setCursor(Qt::BusyCursor);
        toolbox->setCursor( Qt::BusyCursor );
        ++busyNumber;
600
        if (!progress){
601 602 603 604 605 606 607 608
            progress = new QProgressBar(statusBar());
            progress->setMinimum( 0 );
            progress->setMaximum( 0 );
            progress->setFixedSize(250, 17);
            statusBar()->addPermanentWidget(progress);
        }
    } else {
        --busyNumber;
609
        if ( busyNumber < 1 ){
610 611
            this->unsetCursor();
            toolbox->unsetCursor();
612
            if (progress){
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
                statusBar()->removeWidget(progress);
                progress->deleteLater();
                progress = 0;
            }
//             busyNumber = 0;
        }
    }
}

QWidget* MainWindow::createPostEntry(int blog_id, const BilboPost& post)
{
    kDebug();
    PostEntry *temp = new PostEntry( this );
    temp->setAttribute( Qt::WA_DeleteOnClose );
    temp->setCurrentPost(post);
    temp->setCurrentPostBlogId( blog_id );

Laurent Montel's avatar
Laurent Montel committed
630 631 632 633 634 635
    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)),
636 637
             this, SLOT(slotShowStatusMessage(QString,bool)));

Laurent Montel's avatar
Laurent Montel committed
638
    connect( temp, SIGNAL(sigBusy(bool)), this, SLOT(slotBusy(bool)) );
639 640 641 642 643 644 645 646 647 648 649 650 651 652

    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)));
653
    if (mCurrentBlogId == -1)
654 655
        uploadDlg->init( 0 );
    else
Mehrdad Momeny's avatar
Mehrdad Momeny committed
656
        uploadDlg->init( DBMan::self()->blog(mCurrentBlogId) );
657 658
}

659 660
void MainWindow::slotOpenCurrentBlogInBrowser()
{
Mehrdad Momeny's avatar
Mehrdad Momeny committed
661
    if (mCurrentBlogId > -1) {
Mehrdad Momeny's avatar
Mehrdad Momeny committed
662
        KUrl url( DBMan::self()->blog( mCurrentBlogId )->blogUrl() );
663
        if (url.isValid())
Mehrdad Momeny's avatar
Mehrdad Momeny committed
664 665 666
            KToolInvocation::invokeBrowser(url.url());
        else
            KMessageBox::sorry(this, i18n("Cannot find current blog URL."));
667 668
    }
    ///TODO
Laurent Montel's avatar
Cleanup  
Laurent Montel committed
669
    ///else show a message to the user saying that a blog should be selected before.
670 671
}