<commit_before>/*
    This file is part of KOrganizer.

    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <kcmultidialog.h>
#include <ksettings/dialog.h>

#include <libkdepim/categoryeditdialog.h>

#include "calendarview.h"
#include "koprefsdialog.h"
#include "koprefs.h"
#include "koeventeditor.h"
#include "kotodoeditor.h"
#include "kojournaleditor.h"
#include "searchdialog.h"
#include "filtereditdialog.h"
#ifndef KORG_NOARCHIVE
#include "archivedialog.h"
#endif
#include "koviewmanager.h"
#include "koagendaview.h"
#include "koglobals.h"

#include "kodialogmanager.h"
#include "kodialogmanager.moc"

// FIXME: Handle KOEventViewerDialogs in dialog manager. Pass
// KOPrefs::mCompactDialog.

class KODialogManager::DialogManagerVisitor : public IncidenceBase::Visitor
{
  public:
    DialogManagerVisitor() : mDialogManager( 0 ) {}

    bool act( IncidenceBase *incidence, KODialogManager *manager )
    {
      mDialogManager = manager;
      return incidence->accept( *this );
    }

  protected:
    KODialogManager *mDialogManager;
};

class KODialogManager::EditorDialogVisitor :
      public KODialogManager::DialogManagerVisitor
{
  public:
    EditorDialogVisitor() : DialogManagerVisitor(), mEditor( 0 ) {}
    KOIncidenceEditor *editor() const { return mEditor; }
  protected:
    bool visit( Event * ) { mEditor = mDialogManager->getEventEditor(); return mEditor; }
    bool visit( Todo * ) { mEditor = mDialogManager->getTodoEditor(); return mEditor; }
    bool visit( Journal * ) { mEditor = mDialogManager->getJournalEditor(); return mEditor; }
  protected:
    KOIncidenceEditor *mEditor;
};

KODialogManager::KODialogManager( CalendarView *mainView ) :
  QObject(), mMainView( mainView )
{
  mOptionsDialog = 0;
  mSearchDialog = 0;
  mArchiveDialog = 0;
  mFilterEditDialog = 0;

  mCategoryEditDialog = new KPIM::CategoryEditDialog( KOPrefs::instance(), mMainView );
  connect( mainView, SIGNAL( categoriesChanged() ),
           mCategoryEditDialog, SLOT( reload() ) );
  KOGlobals::fitDialogToScreen( mCategoryEditDialog );
}

KODialogManager::~KODialogManager()
{
  delete mOptionsDialog;
  delete mSearchDialog;
#ifndef KORG_NOARCHIVE
  delete mArchiveDialog;
#endif
  delete mFilterEditDialog;
}

void KODialogManager::errorSaveIncidence( QWidget *parent, Incidence *incidence )
{
  KMessageBox::sorry( parent, i18n("Unable to save %1 \"%2\".")
                      .arg( i18n( incidence->type() ) )
                      .arg( incidence->summary() ) );
}

void KODialogManager::showOptionsDialog()
{
  if (!mOptionsDialog) {
#if 0
    mOptionsDialog = new KConfigureDialog();
//    mOptionsDialog = new KConfigureDialog( KConfigureDialog::Configurable );
//    mOptionsDialog = new KConfigureDialog( mMainView );
    connect( mOptionsDialog->dialog(),
             SIGNAL( configCommitted( const QCString & ) ),
             mMainView, SLOT( updateConfig() ) );
#else
    mOptionsDialog = new KCMultiDialog( mMainView, "KorganizerPreferences" );
    connect( mOptionsDialog, SIGNAL( configCommitted( const QCString & ) ),
             mMainView, SLOT( updateConfig() ) );
#if 0
    connect( mOptionsDialog, SIGNAL( applyClicked() ),
             mMainView, SLOT( updateConfig() ) );
    connect( mOptionsDialog, SIGNAL( okClicked() ),
             mMainView, SLOT( updateConfig() ) );
    // @TODO Find a way to do this with KCMultiDialog
    connect(mCategoryEditDialog,SIGNAL(categoryConfigChanged()),
            mOptionsDialog,SLOT(updateCategories()));
#endif

    QStringList modules;

    modules.append( "korganizer_configmain.desktop" );
    modules.append( "korganizer_configtime.desktop" );
    modules.append( "korganizer_configviews.desktop" );
    modules.append( "korganizer_configfonts.desktop" );
    modules.append( "korganizer_configcolors.desktop" );
    modules.append( "korganizer_configgroupscheduling.desktop" );
    modules.append( "korganizer_configgroupautomation.desktop" );
    modules.append( "korganizer_configfreebusy.desktop" );
    modules.append( "korganizer_configplugins.desktop" );
    modules.append( "korganizer_configdesignerfields.desktop" );

    // add them all
    QStringList::iterator mit;
    for ( mit = modules.begin(); mit != modules.end(); ++mit )
      mOptionsDialog->addModule( *mit );
#endif
  }

  mOptionsDialog->show();
  mOptionsDialog->raise();
}

void KODialogManager::showCategoryEditDialog()
{
  mCategoryEditDialog->show();
}

void KODialogManager::showSearchDialog()
{
  if (!mSearchDialog) {
    mSearchDialog = new SearchDialog(mMainView->calendar(),mMainView);
    connect(mSearchDialog,SIGNAL(showIncidenceSignal(Incidence *)),
            mMainView,SLOT(showIncidence(Incidence *)));
    connect(mSearchDialog,SIGNAL(editIncidenceSignal(Incidence *)),
            mMainView,SLOT(editIncidence(Incidence *)));
    connect(mSearchDialog,SIGNAL(deleteIncidenceSignal(Incidence *)),
            mMainView, SLOT(deleteIncidence(Incidence *)));
    connect(mMainView,SIGNAL(closingDown()),mSearchDialog,SLOT(reject()));
  }
  // make sure the widget is on top again
  mSearchDialog->show();
  mSearchDialog->raise();
}

void KODialogManager::showArchiveDialog()
{
#ifndef KORG_NOARCHIVE
  if (!mArchiveDialog) {
    mArchiveDialog = new ArchiveDialog(mMainView->calendar(),mMainView);
    connect(mArchiveDialog,SIGNAL(eventsDeleted()),
            mMainView,SLOT(updateView()));
    connect(mArchiveDialog,SIGNAL(autoArchivingSettingsModified()),
            mMainView,SLOT(slotAutoArchivingSettingsModified()));
  }
  mArchiveDialog->show();
  mArchiveDialog->raise();

  // Workaround.
  QApplication::restoreOverrideCursor();
#endif
}

void KODialogManager::showFilterEditDialog( QPtrList<CalFilter> *filters )
{
  if ( !mFilterEditDialog ) {
    mFilterEditDialog = new FilterEditDialog( filters, mMainView );
    connect( mFilterEditDialog, SIGNAL( filterChanged() ),
             mMainView, SLOT( updateFilter() ) );
    connect( mFilterEditDialog, SIGNAL( editCategories() ),
             mCategoryEditDialog, SLOT( show() ) );
    connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
             mFilterEditDialog, SLOT( updateCategoryConfig() ) );
  }
  mFilterEditDialog->show();
  mFilterEditDialog->raise();
}

KOIncidenceEditor *KODialogManager::getEditor( Incidence *incidence )
{
  if ( !incidence ) return 0;
  EditorDialogVisitor v;
  if ( v.act( incidence, this ) ) {
    return v.editor();
  } else
    return 0;
}

KOEventEditor *KODialogManager::getEventEditor()
{
  KOEventEditor *eventEditor = new KOEventEditor( mMainView->calendar(),
                                                  mMainView );
  connectEditor( eventEditor );
  return eventEditor;
}

void KODialogManager::connectTypeAhead( KOEventEditor *editor,
                                        KOAgendaView *agenda )
{
  if ( editor && agenda ) {
    agenda->setTypeAheadReceiver( editor->typeAheadReceiver() );
    connect( editor, SIGNAL( focusReceivedSignal() ),
             agenda, SLOT( finishTypeAhead() ) );
  }
}

void KODialogManager::connectEditor( KOIncidenceEditor*editor )
{
/*  connect( editor, SIGNAL( deleteIncidenceSignal( Incidence * ) ),
           mMainView, SLOT( deleteIncidence( Incidence * ) ) );*/

  connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
           editor, SLOT( updateCategoryConfig() ) );
  connect( editor, SIGNAL( editCategories() ),
           mCategoryEditDialog, SLOT( show() ) );

  connect( editor, SIGNAL( dialogClose( Incidence * ) ),
           mMainView, SLOT( dialogClosing( Incidence * ) ) );
  connect( editor, SIGNAL( editCanceled( Incidence * ) ),
           mMainView, SLOT( editCanceled( Incidence * ) ) );
  connect( mMainView, SIGNAL( closingDown() ), editor, SLOT( reject() ) );

  connect( editor, SIGNAL( deleteAttendee( Incidence * ) ),
           mMainView, SLOT( cancelAttendees( Incidence * ) ) );
}

KOTodoEditor *KODialogManager::getTodoEditor()
{
  KOTodoEditor *todoEditor = new KOTodoEditor( mMainView->calendar(), mMainView );
  connectEditor( todoEditor );
  return todoEditor;
}

KOJournalEditor *KODialogManager::getJournalEditor()
{
  KOJournalEditor *journalEditor = new KOJournalEditor( mMainView->calendar(), mMainView );
  connectEditor( journalEditor );
  return journalEditor;
}

void KODialogManager::updateSearchDialog()
{
  if (mSearchDialog) mSearchDialog->updateView();
}

<commit_msg>It's a SIGNAL, not a SLOT!<commit_after>/*
    This file is part of KOrganizer.

    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>
    Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <kcmultidialog.h>
#include <ksettings/dialog.h>

#include <libkdepim/categoryeditdialog.h>

#include "calendarview.h"
#include "koprefsdialog.h"
#include "koprefs.h"
#include "koeventeditor.h"
#include "kotodoeditor.h"
#include "kojournaleditor.h"
#include "searchdialog.h"
#include "filtereditdialog.h"
#ifndef KORG_NOARCHIVE
#include "archivedialog.h"
#endif
#include "koviewmanager.h"
#include "koagendaview.h"
#include "koglobals.h"

#include "kodialogmanager.h"
#include "kodialogmanager.moc"

// FIXME: Handle KOEventViewerDialogs in dialog manager. Pass
// KOPrefs::mCompactDialog.

class KODialogManager::DialogManagerVisitor : public IncidenceBase::Visitor
{
  public:
    DialogManagerVisitor() : mDialogManager( 0 ) {}

    bool act( IncidenceBase *incidence, KODialogManager *manager )
    {
      mDialogManager = manager;
      return incidence->accept( *this );
    }

  protected:
    KODialogManager *mDialogManager;
};

class KODialogManager::EditorDialogVisitor :
      public KODialogManager::DialogManagerVisitor
{
  public:
    EditorDialogVisitor() : DialogManagerVisitor(), mEditor( 0 ) {}
    KOIncidenceEditor *editor() const { return mEditor; }
  protected:
    bool visit( Event * ) { mEditor = mDialogManager->getEventEditor(); return mEditor; }
    bool visit( Todo * ) { mEditor = mDialogManager->getTodoEditor(); return mEditor; }
    bool visit( Journal * ) { mEditor = mDialogManager->getJournalEditor(); return mEditor; }
  protected:
    KOIncidenceEditor *mEditor;
};

KODialogManager::KODialogManager( CalendarView *mainView ) :
  QObject(), mMainView( mainView )
{
  mOptionsDialog = 0;
  mSearchDialog = 0;
  mArchiveDialog = 0;
  mFilterEditDialog = 0;

  mCategoryEditDialog = new KPIM::CategoryEditDialog( KOPrefs::instance(), mMainView );
  connect( mainView, SIGNAL( categoriesChanged() ),
           mCategoryEditDialog, SLOT( reload() ) );
  KOGlobals::fitDialogToScreen( mCategoryEditDialog );
}

KODialogManager::~KODialogManager()
{
  delete mOptionsDialog;
  delete mSearchDialog;
#ifndef KORG_NOARCHIVE
  delete mArchiveDialog;
#endif
  delete mFilterEditDialog;
}

void KODialogManager::errorSaveIncidence( QWidget *parent, Incidence *incidence )
{
  KMessageBox::sorry( parent, i18n("Unable to save %1 \"%2\".")
                      .arg( i18n( incidence->type() ) )
                      .arg( incidence->summary() ) );
}

void KODialogManager::showOptionsDialog()
{
  if (!mOptionsDialog) {
#if 0
    mOptionsDialog = new KConfigureDialog();
//    mOptionsDialog = new KConfigureDialog( KConfigureDialog::Configurable );
//    mOptionsDialog = new KConfigureDialog( mMainView );
    connect( mOptionsDialog->dialog(),
             SIGNAL( configCommitted( const QCString & ) ),
             mMainView, SLOT( updateConfig() ) );
#else
    mOptionsDialog = new KCMultiDialog( mMainView, "KorganizerPreferences" );
    connect( mOptionsDialog, SIGNAL( configCommitted( const QCString & ) ),
             mMainView, SLOT( updateConfig() ) );
#if 0
    connect( mOptionsDialog, SIGNAL( applyClicked() ),
             mMainView, SLOT( updateConfig() ) );
    connect( mOptionsDialog, SIGNAL( okClicked() ),
             mMainView, SLOT( updateConfig() ) );
    // @TODO Find a way to do this with KCMultiDialog
    connect(mCategoryEditDialog,SIGNAL(categoryConfigChanged()),
            mOptionsDialog,SLOT(updateCategories()));
#endif

    QStringList modules;

    modules.append( "korganizer_configmain.desktop" );
    modules.append( "korganizer_configtime.desktop" );
    modules.append( "korganizer_configviews.desktop" );
    modules.append( "korganizer_configfonts.desktop" );
    modules.append( "korganizer_configcolors.desktop" );
    modules.append( "korganizer_configgroupscheduling.desktop" );
    modules.append( "korganizer_configgroupautomation.desktop" );
    modules.append( "korganizer_configfreebusy.desktop" );
    modules.append( "korganizer_configplugins.desktop" );
    modules.append( "korganizer_configdesignerfields.desktop" );

    // add them all
    QStringList::iterator mit;
    for ( mit = modules.begin(); mit != modules.end(); ++mit )
      mOptionsDialog->addModule( *mit );
#endif
  }

  mOptionsDialog->show();
  mOptionsDialog->raise();
}

void KODialogManager::showCategoryEditDialog()
{
  mCategoryEditDialog->show();
}

void KODialogManager::showSearchDialog()
{
  if (!mSearchDialog) {
    mSearchDialog = new SearchDialog(mMainView->calendar(),mMainView);
    connect(mSearchDialog,SIGNAL(showIncidenceSignal(Incidence *)),
            mMainView,SLOT(showIncidence(Incidence *)));
    connect(mSearchDialog,SIGNAL(editIncidenceSignal(Incidence *)),
            mMainView,SLOT(editIncidence(Incidence *)));
    connect(mSearchDialog,SIGNAL(deleteIncidenceSignal(Incidence *)),
            mMainView, SLOT(deleteIncidence(Incidence *)));
    connect(mMainView,SIGNAL(closingDown()),mSearchDialog,SLOT(reject()));
  }
  // make sure the widget is on top again
  mSearchDialog->show();
  mSearchDialog->raise();
}

void KODialogManager::showArchiveDialog()
{
#ifndef KORG_NOARCHIVE
  if (!mArchiveDialog) {
    mArchiveDialog = new ArchiveDialog(mMainView->calendar(),mMainView);
    connect(mArchiveDialog,SIGNAL(eventsDeleted()),
            mMainView,SLOT(updateView()));
    connect(mArchiveDialog,SIGNAL(autoArchivingSettingsModified()),
            mMainView,SLOT(slotAutoArchivingSettingsModified()));
  }
  mArchiveDialog->show();
  mArchiveDialog->raise();

  // Workaround.
  QApplication::restoreOverrideCursor();
#endif
}

void KODialogManager::showFilterEditDialog( QPtrList<CalFilter> *filters )
{
  if ( !mFilterEditDialog ) {
    mFilterEditDialog = new FilterEditDialog( filters, mMainView );
    connect( mFilterEditDialog, SIGNAL( filterChanged() ),
             mMainView, SLOT( updateFilter() ) );
    connect( mFilterEditDialog, SIGNAL( editCategories() ),
             mCategoryEditDialog, SLOT( show() ) );
    connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
             mFilterEditDialog, SLOT( updateCategoryConfig() ) );
  }
  mFilterEditDialog->show();
  mFilterEditDialog->raise();
}

KOIncidenceEditor *KODialogManager::getEditor( Incidence *incidence )
{
  if ( !incidence ) return 0;
  EditorDialogVisitor v;
  if ( v.act( incidence, this ) ) {
    return v.editor();
  } else
    return 0;
}

KOEventEditor *KODialogManager::getEventEditor()
{
  KOEventEditor *eventEditor = new KOEventEditor( mMainView->calendar(),
                                                  mMainView );
  connectEditor( eventEditor );
  return eventEditor;
}

void KODialogManager::connectTypeAhead( KOEventEditor *editor,
                                        KOAgendaView *agenda )
{
  if ( editor && agenda ) {
    agenda->setTypeAheadReceiver( editor->typeAheadReceiver() );
    connect( editor, SIGNAL( focusReceivedSignal() ),
             agenda, SLOT( finishTypeAhead() ) );
  }
}

void KODialogManager::connectEditor( KOIncidenceEditor*editor )
{
/*  connect( editor, SIGNAL( deleteIncidenceSignal( Incidence * ) ),
           mMainView, SLOT( deleteIncidence( Incidence * ) ) );*/

  connect( mCategoryEditDialog, SIGNAL( categoryConfigChanged() ),
           editor, SLOT( updateCategoryConfig() ) );
  connect( editor, SIGNAL( editCategories() ),
           mCategoryEditDialog, SLOT( show() ) );

  connect( editor, SIGNAL( dialogClose( Incidence * ) ),
           mMainView, SLOT( dialogClosing( Incidence * ) ) );
  connect( editor, SIGNAL( editCanceled( Incidence * ) ),
           mMainView, SLOT( editCanceled( Incidence * ) ) );
  connect( mMainView, SIGNAL( closingDown() ), editor, SLOT( reject() ) );

  connect( editor, SIGNAL( deleteAttendee( Incidence * ) ),
           mMainView, SIGNAL( cancelAttendees( Incidence * ) ) );
}

KOTodoEditor *KODialogManager::getTodoEditor()
{
  KOTodoEditor *todoEditor = new KOTodoEditor( mMainView->calendar(), mMainView );
  connectEditor( todoEditor );
  return todoEditor;
}

KOJournalEditor *KODialogManager::getJournalEditor()
{
  KOJournalEditor *journalEditor = new KOJournalEditor( mMainView->calendar(), mMainView );
  connectEditor( journalEditor );
  return journalEditor;
}

void KODialogManager::updateSearchDialog()
{
  if (mSearchDialog) mSearchDialog->updateView();
}

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of duihome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "launcher.h"
#include "desktopview.h"
#include "desktop.h"
#include "notificationarea.h"
#include "mainwindow.h"
#include "switcher.h"
#include "statusindicator.h"
#include "contextframeworkcontext.h"
#include "appletspace.h"
#include "quicklaunchbar.h"

#include <DuiViewCreator>
#include <DuiDeviceProfile>
#include <DuiSceneManager>
#include <DuiModalSceneWindow>
#include <DuiPannableViewport>
#include <DuiApplication>
#include <DuiOverlay>
#include <QGraphicsLinearLayout>

#ifdef BENCHMARKS_ON
#include <QTextStream>
#include <QFile>
#include <QTimer>
#include <QTime>
#include <QFileSystemWatcher>
#include <QDir>

// These should really be private variables if one has more than one
// instance of Desktop
static bool benchmarking = false;
static QTime lastUpdate;
static int frameCount = 0;
static int fps = 0;

const int MillisecsInSec = 1000;
const int FpsRefreshInterval = 1000;

void DesktopView::writeFps()
{
    QFile file("/tmp/duihome_benchmarks/benchmark_results.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&file);

    QString fpsString = QString::number(fps);
    QDateTime now = QDateTime::currentDateTime();

    QString nowString = now.toString(Qt::ISODate);
    ts << fpsString << " " << nowString << endl;

    file.close();
}

void DesktopView::startBenchmarking()
{
    frameCount = 0;
    fps = 0;
    lastUpdate = QTime::currentTime();
    benchmarking = true;

    update();
}

void DesktopView::stopBenchmarking()
{
    benchmarking = false;
}
#endif

DesktopView::DesktopView(Desktop *desktop) :
    DuiWidgetView(desktop),
    switcher(new Switcher),
    quickLaunchBar(new QuickLaunchBar),
    quickLaunchBarWindow(new DuiOverlay),
    launcher(new Launcher),
    launcherWindow(new DuiModalSceneWindow),
    launcherViewport(new DuiPannableViewport(launcherWindow)),
    appletSpace(new AppletSpace),
    appletSpaceWindow(new DuiModalSceneWindow),
    appletSpaceViewport(new DuiPannableViewport(appletSpaceWindow))
{
    // Create the main layout that contains the switcher etc.
    QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    desktop->setLayout(mainLayout);

    // Create phone network status indicator
    phoneNetworkIndicator = new PhoneNetworkStatusIndicator(contextFrameworkContext, desktop);

    // Create switcher
    mainLayout->addItem(switcher);
    connect(desktop, SIGNAL(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)),
            switcher, SLOT(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)));

    // Fill the rest with empty space
    mainLayout->addStretch();

    // Create a quick launch bar
    quickLaunchBar = new QuickLaunchBar;
    connect(quickLaunchBar, SIGNAL(toggleLauncherButtonClicked()), this, SLOT(toggleLauncher()));
    connect(quickLaunchBar, SIGNAL(toggleAppletSpaceButtonClicked()), this, SLOT(toggleAppletSpace()));

    // Create a layout for the quick launch bar window
    QGraphicsLinearLayout *windowLayout = new QGraphicsLinearLayout();
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addItem(quickLaunchBar);
    quickLaunchBarWindow->setLayout(windowLayout);
    quickLaunchBarWindow->setObjectName("QuickLaunchBarOverlay");
    MainWindow::instance()->sceneManager()->showWindowNow(quickLaunchBarWindow);

    // Put the launcher inside a pannable viewport
    launcherViewport->setWidget(launcher);
    launcherViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
    launcherViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());

    // Create a layout for the launcher window
    windowLayout = new QGraphicsLinearLayout();
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addItem(launcherViewport);
    launcherWindow->setLayout(windowLayout);
    launcherWindow->setObjectName("LauncherWindow");
    MainWindow::instance()->sceneManager()->hideWindowNow(launcherWindow);

    // Put the applet space inside a pannable viewport
    connect(appletSpace, SIGNAL(closed()), this, SLOT(toggleAppletSpace()));
    appletSpaceViewport->setWidget(appletSpace);
    appletSpaceViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
    appletSpaceViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());

    // Create a layout for the applet space window
    windowLayout = new QGraphicsLinearLayout();
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addItem(appletSpaceViewport);
    appletSpaceWindow->setLayout(windowLayout);
    appletSpaceWindow->setObjectName("AppletSpaceWindow");
    MainWindow::instance()->sceneManager()->hideWindowNow(appletSpaceWindow);

#ifdef BENCHMARKS_ON
    QDir dir;
    if(!dir.exists("/tmp/duihome_benchmarks")) {
        dir.mkdir("/tmp/duihome_benchmarks");
    }

    connect(DuiApplication::instance(), SIGNAL(startBenchmarking()), this, SLOT(startBenchmarking()));
    connect(DuiApplication::instance(), SIGNAL(stopBenchmarking()), this, SLOT(stopBenchmarking()));
#endif
}

DesktopView::~DesktopView()
{
    delete launcherWindow;
}

#ifdef BENCHMARKS_ON
void DesktopView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    DuiWidgetView::paint(painter, option, widget);

    if (benchmarking) {
        QTime now = QTime::currentTime();
        ++frameCount;

        if (lastUpdate.msecsTo(now) > FpsRefreshInterval) {
            fps = (MillisecsInSec * frameCount) / (lastUpdate.msecsTo(now));
            frameCount = 0;
            lastUpdate = now;

            writeFps();
        }

        update();
    }
}
#endif

void DesktopView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *) const
{
    // Draw the background image
    const QPixmap *pixmap = style()->desktopBackgroundImage();
    if (pixmap != NULL) {
        // Always draw the background texture without rotation
        const QTransform w = painter->worldTransform();
        painter->setWorldTransform(QTransform());

        // Use the actual screen size for painting the background because it does not rotate
        QPointF p = w.map(QPointF(0, 0));
        QPointF offset(-p.x() + w.dx(), -p.y() + w.dy());
        painter->drawTiledPixmap(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()), *pixmap, offset);

        // Reset the transform
        painter->setWorldTransform(w);
    }

    if (!model()->notificationAreaOpen()) {
        // Draw the top image
        pixmap = style()->desktopBackgroundTop();
        if (pixmap != NULL) {
            painter->drawTiledPixmap(QRectF(0, -pixmap->height(), geometry().width(), pixmap->height()), *pixmap);
        }
    }

    // Draw the bottom image
    pixmap = style()->desktopBackgroundBottom();
    if (pixmap != NULL) {
        painter->drawTiledPixmap(QRectF(0, geometry().height(), geometry().width(), pixmap->height()), *pixmap);
    }
}

QRectF DesktopView::boundingRect() const
{
    // The area to be drawn includes the top and bottom images in addition to the actual content
    int top = 0;
    int bottom = 0;
    const QPixmap *topPixmap = style()->desktopBackgroundTop();
    const QPixmap *bottomPixmap = style()->desktopBackgroundBottom();

    if (topPixmap != NULL) {
        top = topPixmap->height();
    }
    if (bottomPixmap != NULL) {
        bottom = bottomPixmap->height();
    }

    QRectF rect(0, -top, geometry().width(), geometry().height() + top + bottom);
    return rect.united(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()));
}

void DesktopView::toggleLauncher()
{
    if (launcherWindow->isVisible()) {
        hideLauncher();
    } else {
        showLauncher();
    }
}

void DesktopView::showLauncher()
{
    launcher->setEnabled(true);
    launcher->openRootCategory();
    MainWindow::instance()->sceneManager()->showWindow(launcherWindow);

    // Set the launcher window below other modal scene windows
    // @todo TODO get rid of the hardcoded value when DuiSceneManager enables dynamic allocation of Z values
    launcherWindow->parentItem()->setZValue(300);
}

void DesktopView::hideLauncher()
{
    // Disable the launcher so that during the disappear animation of
    // the dialog it's not possible to launch another application
    launcher->setEnabled(false);

    // Scroll the launcher above the screen
    MainWindow::instance()->sceneManager()->hideWindow(launcherWindow);
}

void DesktopView::toggleAppletSpace()
{
    if (appletSpaceWindow->isVisible()) {
        appletSpaceWindow->disappear();
        appletSpace->setEnabled(false);
    } else {
        appletSpaceWindow->appear();
        appletSpace->setEnabled(true);
    }
}

void DesktopView::setGeometry(const QRectF &rect)
{
    DuiWidgetView::setGeometry(rect);

    // Set the launcher viewport to the size of the desktop
    launcherViewport->setMinimumSize(rect.size());
    launcherViewport->setMaximumSize(rect.size());
}

DUI_REGISTER_VIEW_NEW(DesktopView, Desktop)
<commit_msg>Changes: Moved the file openrations for benchmarking from writeFps() to start/stopBenchmarking()<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of duihome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "launcher.h"
#include "desktopview.h"
#include "desktop.h"
#include "notificationarea.h"
#include "mainwindow.h"
#include "switcher.h"
#include "statusindicator.h"
#include "contextframeworkcontext.h"
#include "appletspace.h"
#include "quicklaunchbar.h"

#include <DuiViewCreator>
#include <DuiDeviceProfile>
#include <DuiSceneManager>
#include <DuiModalSceneWindow>
#include <DuiPannableViewport>
#include <DuiApplication>
#include <DuiOverlay>
#include <QGraphicsLinearLayout>

#ifdef BENCHMARKS_ON
#include <QTextStream>
#include <QFile>
#include <QTimer>
#include <QTime>
#include <QFileSystemWatcher>
#include <QDir>

// These should really be private variables if one has more than one
// instance of Desktop
static bool benchmarking = false;
static QTime lastUpdate;
static int frameCount = 0;
static int fps = 0;
static QFile* fpsFile;
static QTextStream* fpsStream;

const int MillisecsInSec = 1000;
const int FpsRefreshInterval = 1000;

void DesktopView::writeFps()
{
    if (!benchmarking)
        return;

    QString fpsString = QString::number(fps);
    QDateTime now = QDateTime::currentDateTime();
    QString nowString = now.toString(Qt::ISODate);

    *fpsStream << fpsString << " " << nowString << endl;
    fpsStream->flush();
}

void DesktopView::startBenchmarking()
{
    fpsFile = new QFile("/tmp/duihome_benchmarks/benchmark_results.txt");
    fpsFile->open(QIODevice::WriteOnly | QIODevice::Append);
    fpsStream = new QTextStream(fpsFile);

    frameCount = 0;
    fps = 0;
    lastUpdate = QTime::currentTime();
    benchmarking = true;

    update();
}

void DesktopView::stopBenchmarking()
{
    benchmarking = false;

    delete fpsStream;
    delete fpsFile;
}
#endif

DesktopView::DesktopView(Desktop *desktop) :
    DuiWidgetView(desktop),
    switcher(new Switcher),
    quickLaunchBar(new QuickLaunchBar),
    quickLaunchBarWindow(new DuiOverlay),
    launcher(new Launcher),
    launcherWindow(new DuiModalSceneWindow),
    launcherViewport(new DuiPannableViewport(launcherWindow)),
    appletSpace(new AppletSpace),
    appletSpaceWindow(new DuiModalSceneWindow),
    appletSpaceViewport(new DuiPannableViewport(appletSpaceWindow))
{
    // Create the main layout that contains the switcher etc.
    QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout(Qt::Vertical);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(0);
    desktop->setLayout(mainLayout);

    // Create phone network status indicator
    phoneNetworkIndicator = new PhoneNetworkStatusIndicator(contextFrameworkContext, desktop);

    // Create switcher
    mainLayout->addItem(switcher);
    connect(desktop, SIGNAL(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)),
            switcher, SLOT(viewportSizePosChanged(const QSizeF &, const QRectF &, const QPointF &)));

    // Fill the rest with empty space
    mainLayout->addStretch();

    // Create a quick launch bar
    quickLaunchBar = new QuickLaunchBar;
    connect(quickLaunchBar, SIGNAL(toggleLauncherButtonClicked()), this, SLOT(toggleLauncher()));
    connect(quickLaunchBar, SIGNAL(toggleAppletSpaceButtonClicked()), this, SLOT(toggleAppletSpace()));

    // Create a layout for the quick launch bar window
    QGraphicsLinearLayout *windowLayout = new QGraphicsLinearLayout();
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addItem(quickLaunchBar);
    quickLaunchBarWindow->setLayout(windowLayout);
    quickLaunchBarWindow->setObjectName("QuickLaunchBarOverlay");
    MainWindow::instance()->sceneManager()->showWindowNow(quickLaunchBarWindow);

    // Put the launcher inside a pannable viewport
    launcherViewport->setWidget(launcher);
    launcherViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
    launcherViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());

    // Create a layout for the launcher window
    windowLayout = new QGraphicsLinearLayout();
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addItem(launcherViewport);
    launcherWindow->setLayout(windowLayout);
    launcherWindow->setObjectName("LauncherWindow");
    MainWindow::instance()->sceneManager()->hideWindowNow(launcherWindow);

    // Put the applet space inside a pannable viewport
    connect(appletSpace, SIGNAL(closed()), this, SLOT(toggleAppletSpace()));
    appletSpaceViewport->setWidget(appletSpace);
    appletSpaceViewport->setMinimumSize(DuiApplication::activeWindow()->visibleSceneSize());
    appletSpaceViewport->setMaximumSize(DuiApplication::activeWindow()->visibleSceneSize());

    // Create a layout for the applet space window
    windowLayout = new QGraphicsLinearLayout();
    windowLayout->setContentsMargins(0, 0, 0, 0);
    windowLayout->addItem(appletSpaceViewport);
    appletSpaceWindow->setLayout(windowLayout);
    appletSpaceWindow->setObjectName("AppletSpaceWindow");
    MainWindow::instance()->sceneManager()->hideWindowNow(appletSpaceWindow);

#ifdef BENCHMARKS_ON
    QDir dir;
    if(!dir.exists("/tmp/duihome_benchmarks")) {
        dir.mkdir("/tmp/duihome_benchmarks");
    }

    connect(DuiApplication::instance(), SIGNAL(startBenchmarking()), this, SLOT(startBenchmarking()));
    connect(DuiApplication::instance(), SIGNAL(stopBenchmarking()), this, SLOT(stopBenchmarking()));
#endif
}

DesktopView::~DesktopView()
{
    delete launcherWindow;
}

#ifdef BENCHMARKS_ON
void DesktopView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    DuiWidgetView::paint(painter, option, widget);

    if (benchmarking) {
        QTime now = QTime::currentTime();
        ++frameCount;

        if (lastUpdate.msecsTo(now) > FpsRefreshInterval) {
            fps = (MillisecsInSec * frameCount) / (lastUpdate.msecsTo(now));
            frameCount = 0;
            lastUpdate = now;

            writeFps();
        }

        update();
    }
}
#endif

void DesktopView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *) const
{
    // Draw the background image
    const QPixmap *pixmap = style()->desktopBackgroundImage();
    if (pixmap != NULL) {
        // Always draw the background texture without rotation
        const QTransform w = painter->worldTransform();
        painter->setWorldTransform(QTransform());

        // Use the actual screen size for painting the background because it does not rotate
        QPointF p = w.map(QPointF(0, 0));
        QPointF offset(-p.x() + w.dx(), -p.y() + w.dy());
        painter->drawTiledPixmap(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()), *pixmap, offset);

        // Reset the transform
        painter->setWorldTransform(w);
    }

    if (!model()->notificationAreaOpen()) {
        // Draw the top image
        pixmap = style()->desktopBackgroundTop();
        if (pixmap != NULL) {
            painter->drawTiledPixmap(QRectF(0, -pixmap->height(), geometry().width(), pixmap->height()), *pixmap);
        }
    }

    // Draw the bottom image
    pixmap = style()->desktopBackgroundBottom();
    if (pixmap != NULL) {
        painter->drawTiledPixmap(QRectF(0, geometry().height(), geometry().width(), pixmap->height()), *pixmap);
    }
}

QRectF DesktopView::boundingRect() const
{
    // The area to be drawn includes the top and bottom images in addition to the actual content
    int top = 0;
    int bottom = 0;
    const QPixmap *topPixmap = style()->desktopBackgroundTop();
    const QPixmap *bottomPixmap = style()->desktopBackgroundBottom();

    if (topPixmap != NULL) {
        top = topPixmap->height();
    }
    if (bottomPixmap != NULL) {
        bottom = bottomPixmap->height();
    }

    QRectF rect(0, -top, geometry().width(), geometry().height() + top + bottom);
    return rect.united(QRectF(0, 0, DuiDeviceProfile::instance()->resolution().width(), DuiDeviceProfile::instance()->resolution().height()));
}

void DesktopView::toggleLauncher()
{
    if (launcherWindow->isVisible()) {
        hideLauncher();
    } else {
        showLauncher();
    }
}

void DesktopView::showLauncher()
{
    launcher->setEnabled(true);
    launcher->openRootCategory();
    MainWindow::instance()->sceneManager()->showWindow(launcherWindow);

    // Set the launcher window below other modal scene windows
    // @todo TODO get rid of the hardcoded value when DuiSceneManager enables dynamic allocation of Z values
    launcherWindow->parentItem()->setZValue(300);
}

void DesktopView::hideLauncher()
{
    // Disable the launcher so that during the disappear animation of
    // the dialog it's not possible to launch another application
    launcher->setEnabled(false);

    // Scroll the launcher above the screen
    MainWindow::instance()->sceneManager()->hideWindow(launcherWindow);
}

void DesktopView::toggleAppletSpace()
{
    if (appletSpaceWindow->isVisible()) {
        appletSpaceWindow->disappear();
        appletSpace->setEnabled(false);
    } else {
        appletSpaceWindow->appear();
        appletSpace->setEnabled(true);
    }
}

void DesktopView::setGeometry(const QRectF &rect)
{
    DuiWidgetView::setGeometry(rect);

    // Set the launcher viewport to the size of the desktop
    launcherViewport->setMinimumSize(rect.size());
    launcherViewport->setMaximumSize(rect.size());
}

DUI_REGISTER_VIEW_NEW(DesktopView, Desktop)
<|endoftext|>


<commit_before>/* fileInstaller.cc			KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/

/*
** 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) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

static const char *fileinstaller_id =
	"$Id$";

#ifndef _KPILOT_OPTIONS_H
#include "options.h"
#endif

#include <unistd.h>

#ifndef QSTRING_H
#include <qstring.h>
#endif
#ifndef QSTRLIST_H
#include <qstrlist.h>
#endif
#ifndef QDIR_H
#include <qdir.h>
#endif

#ifndef _KGLOBAL_H
#include <kglobal.h>
#endif
#ifndef _KSTDDIRS_H
#include <kstddirs.h>
#endif
#ifndef _KURL_H
#include <kurl.h>
#endif
#ifndef _KIO_NETACCESS_H
#include <kio/netaccess.h>
#endif

#include "fileInstaller.moc"

FileInstaller::FileInstaller() :
	enabled(true)
{
	FUNCTIONSETUP;

	fDirName = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/pending_install/"));
	fPendingCopies = 0;

	(void) fileinstaller_id;
}

/* virtual */ FileInstaller::~FileInstaller()
{
	FUNCTIONSETUP;
}

void FileInstaller::clearPending()
{
	FUNCTIONSETUP;

	unsigned int i;

	QDir installDir(fDirName);

	// Start from 2 to skip . and ..
	//
	for (i = 2; i < installDir.count(); i++)
	{
		QFile::remove(fDirName + installDir[i]);
	}

	if (i > 2)
	{
		emit filesChanged();
	}
}

/* virtual */ bool FileInstaller::runCopy(const QString & s)
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif

	KURL srcName(s);
	KURL destDir(fDirName + CSL1("/") + srcName.filename());

	return KIO::NetAccess::copy(srcName, destDir);
}

void FileInstaller::addFiles(const QStringList & fileList)
{
	FUNCTIONSETUP;

	if (!enabled) return;

	unsigned int succ = 0;

	for(QStringList::ConstIterator it = fileList.begin();
	    it != fileList.end(); ++it)
	{
		if (runCopy(*it))
			succ++;
	}

	if (succ)
	{
		emit filesChanged();
	}
}

void FileInstaller::addFile(const QString & file)
{
	FUNCTIONSETUP;

	if (!enabled) return;

	if (runCopy(file))
	{
		emit(filesChanged());
	}
}

/* slot */ void FileInstaller::copyCompleted()
{
	FUNCTIONSETUP;
}

const QStringList FileInstaller::fileNames() const
{
	FUNCTIONSETUP;

	QDir installDir(fDirName);

	return installDir.entryList(QDir::Files |
		QDir::NoSymLinks | QDir::Readable);
}

/* slot */ void FileInstaller::setEnabled(bool b)
{
	FUNCTIONSETUP;
	enabled=b;
}

<commit_msg>Use the new methods instead of deprecates ones.<commit_after>/* fileInstaller.cc			KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/

/*
** 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) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

static const char *fileinstaller_id =
	"$Id$";

#ifndef _KPILOT_OPTIONS_H
#include "options.h"
#endif

#include <unistd.h>

#ifndef QSTRING_H
#include <qstring.h>
#endif
#ifndef QSTRLIST_H
#include <qstrlist.h>
#endif
#ifndef QDIR_H
#include <qdir.h>
#endif

#ifndef _KGLOBAL_H
#include <kglobal.h>
#endif
#ifndef _KSTDDIRS_H
#include <kstddirs.h>
#endif
#ifndef _KURL_H
#include <kurl.h>
#endif
#ifndef _KIO_NETACCESS_H
#include <kio/netaccess.h>
#endif

#include "fileInstaller.moc"

FileInstaller::FileInstaller() :
	enabled(true)
{
	FUNCTIONSETUP;

	fDirName = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/pending_install/"));
	fPendingCopies = 0;

	(void) fileinstaller_id;
}

/* virtual */ FileInstaller::~FileInstaller()
{
	FUNCTIONSETUP;
}

void FileInstaller::clearPending()
{
	FUNCTIONSETUP;

	unsigned int i;

	QDir installDir(fDirName);

	// Start from 2 to skip . and ..
	//
	for (i = 2; i < installDir.count(); i++)
	{
		QFile::remove(fDirName + installDir[i]);
	}

	if (i > 2)
	{
		emit filesChanged();
	}
}

/* virtual */ bool FileInstaller::runCopy(const QString & s)
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif

	KURL srcName(s);
	KURL destDir(fDirName + CSL1("/") + srcName.filename());

	return KIO::NetAccess::copy(srcName, destDir, 0L);
}

void FileInstaller::addFiles(const QStringList & fileList)
{
	FUNCTIONSETUP;

	if (!enabled) return;

	unsigned int succ = 0;

	for(QStringList::ConstIterator it = fileList.begin();
	    it != fileList.end(); ++it)
	{
		if (runCopy(*it))
			succ++;
	}

	if (succ)
	{
		emit filesChanged();
	}
}

void FileInstaller::addFile(const QString & file)
{
	FUNCTIONSETUP;

	if (!enabled) return;

	if (runCopy(file))
	{
		emit(filesChanged());
	}
}

/* slot */ void FileInstaller::copyCompleted()
{
	FUNCTIONSETUP;
}

const QStringList FileInstaller::fileNames() const
{
	FUNCTIONSETUP;

	QDir installDir(fDirName);

	return installDir.entryList(QDir::Files |
		QDir::NoSymLinks | QDir::Readable);
}

/* slot */ void FileInstaller::setEnabled(bool b)
{
	FUNCTIONSETUP;
	enabled=b;
}

<|endoftext|>


<commit_before>/* KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/

/*
** 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) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

static const char *fileinstaller_id =
	"$Id$";

#include "options.h"

#include <unistd.h>

#include <qstring.h>
#include <qstrlist.h>
#include <qdir.h>

#include <kglobal.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>

#include "fileInstaller.moc"

FileInstaller::FileInstaller() :
	enabled(true)
{
	FUNCTIONSETUP;

	fDirName = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/pending_install/"));
	fPendingCopies = 0;

	(void) fileinstaller_id;
}

/* virtual */ FileInstaller::~FileInstaller()
{
	FUNCTIONSETUP;
}

void FileInstaller::clearPending()
{
	FUNCTIONSETUP;

	unsigned int i;

	QDir installDir(fDirName);

	// Start from 2 to skip . and ..
	//
	for (i = 2; i < installDir.count(); i++)
	{
		QFile::remove(fDirName + installDir[i]);
	}

	if (i > 2)
	{
		emit filesChanged();
	}
}

/* virtual */ bool FileInstaller::runCopy(const QString & s, QWidget* w )
{
	FUNCTIONSETUP;

	if(!(s.endsWith("pdb", false) || s.endsWith("prc", false))) {
		KMessageBox::detailedSorry(w, i18n("Cannot install %1").arg(s),
			i18n("Only PalmOS database files (like *.pdb and *.prc) can be installed by the file installer."));
		return false;
	}

#ifdef DEBUG
	DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif

	KURL srcName(s);
	KURL destDir(fDirName + CSL1("/") + srcName.filename());

#if KDE_IS_VERSION(3,1,9)
	return KIO::NetAccess::copy(srcName, destDir, w);
#else
	return KIO::NetAccess::copy(srcName,destDir);
#endif
}

void FileInstaller::addFiles(const QStringList & fileList, QWidget* w)
{
	FUNCTIONSETUP;

	if (!enabled) return;

	unsigned int succ = 0;

	for(QStringList::ConstIterator it = fileList.begin();
	    it != fileList.end(); ++it)
	{
		if (runCopy( *it, w ))
			succ++;
	}

	if (succ)
	{
		emit filesChanged();
	}
}

void FileInstaller::addFile( const QString & file, QWidget* w )
{
	FUNCTIONSETUP;

	if (!enabled) return;

	if (runCopy(file, w))
	{
		emit(filesChanged());
	}
}

/* slot */ void FileInstaller::copyCompleted()
{
	FUNCTIONSETUP;
}

const QStringList FileInstaller::fileNames() const
{
	FUNCTIONSETUP;

	QDir installDir(fDirName);

	return installDir.entryList(QDir::Files |
		QDir::NoSymLinks | QDir::Readable);
}

/* slot */ void FileInstaller::setEnabled(bool b)
{
	FUNCTIONSETUP;
	enabled=b;
}

<commit_msg>KDE_NO_COMPAT fixes<commit_after>/* KPilot
**
** Copyright (C) 1998-2001 by Dan Pilone
**
** This is a class that does "the work" of adding and deleting
** files in the pending_install directory of KPilot. It is used
** by the fileInstallWidget and by the daemon's drag-and-drop
** file accepter.
*/

/*
** 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) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

static const char *fileinstaller_id =
	"$Id$";

#include "options.h"

#include <unistd.h>

#include <qstring.h>
#include <qstrlist.h>
#include <qdir.h>

#include <kglobal.h>
#include <kstandarddirs.h>
#include <kurl.h>
#include <kio/netaccess.h>
#include <kmessagebox.h>

#include "fileInstaller.moc"

FileInstaller::FileInstaller() :
	enabled(true)
{
	FUNCTIONSETUP;

	fDirName = KGlobal::dirs()->saveLocation("data",
		CSL1("kpilot/pending_install/"));
	fPendingCopies = 0;

	(void) fileinstaller_id;
}

/* virtual */ FileInstaller::~FileInstaller()
{
	FUNCTIONSETUP;
}

void FileInstaller::clearPending()
{
	FUNCTIONSETUP;

	unsigned int i;

	QDir installDir(fDirName);

	// Start from 2 to skip . and ..
	//
	for (i = 2; i < installDir.count(); i++)
	{
		QFile::remove(fDirName + installDir[i]);
	}

	if (i > 2)
	{
		emit filesChanged();
	}
}

/* virtual */ bool FileInstaller::runCopy(const QString & s, QWidget* w )
{
	FUNCTIONSETUP;

	if(!(s.endsWith("pdb", false) || s.endsWith("prc", false))) {
		KMessageBox::detailedSorry(w, i18n("Cannot install %1").arg(s),
			i18n("Only PalmOS database files (like *.pdb and *.prc) can be installed by the file installer."));
		return false;
	}

#ifdef DEBUG
	DEBUGDAEMON << fname << ": Copying " << s << endl;
#endif

	KURL srcName(s);
	KURL destDir(fDirName + CSL1("/") + srcName.fileName());

#if KDE_IS_VERSION(3,1,9)
	return KIO::NetAccess::copy(srcName, destDir, w);
#else
	return KIO::NetAccess::copy(srcName,destDir);
#endif
}

void FileInstaller::addFiles(const QStringList & fileList, QWidget* w)
{
	FUNCTIONSETUP;

	if (!enabled) return;

	unsigned int succ = 0;

	for(QStringList::ConstIterator it = fileList.begin();
	    it != fileList.end(); ++it)
	{
		if (runCopy( *it, w ))
			succ++;
	}

	if (succ)
	{
		emit filesChanged();
	}
}

void FileInstaller::addFile( const QString & file, QWidget* w )
{
	FUNCTIONSETUP;

	if (!enabled) return;

	if (runCopy(file, w))
	{
		emit(filesChanged());
	}
}

/* slot */ void FileInstaller::copyCompleted()
{
	FUNCTIONSETUP;
}

const QStringList FileInstaller::fileNames() const
{
	FUNCTIONSETUP;

	QDir installDir(fDirName);

	return installDir.entryList(QDir::Files |
		QDir::NoSymLinks | QDir::Readable);
}

/* slot */ void FileInstaller::setEnabled(bool b)
{
	FUNCTIONSETUP;
	enabled=b;
}

<|endoftext|>


<commit_before>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "task.h"

#include <libkcal/todo.h>
#include <kdebug.h>

using namespace Kolab;

KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
  Task task( tz );
  task.load( xml );
  KCal::Todo* todo = new KCal::Todo();
  task.saveTo( todo );
  return todo;
}

QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
  Task task( tz, todo );
  return task.saveXML();
}

Task::Task( const QString& tz, KCal::Todo* task )
  : Incidence( tz ), mPriority( 5 ), mPercentCompleted( 0 ),
    mStatus( KCal::Incidence::StatusNone ),
    mHasStartDate( false ), mHasDueDate( false ),
    mHasCompletedDate( false )
{
  if ( task )
    setFields( task );
}

Task::~Task()
{
}

void Task::setPriority( int priority )
{
  mPriority = priority;
}

int Task::priority() const
{
  return mPriority;
}

void Task::setPercentCompleted( int percent )
{
  mPercentCompleted = percent;
}

int Task::percentCompleted() const
{
  return mPercentCompleted;
}

void Task::setStatus( KCal::Incidence::Status status )
{
  mStatus = status;
}

KCal::Incidence::Status Task::status() const
{
  return mStatus;
}

void Task::setParent( const QString& parentUid )
{
  mParent = parentUid;
}

QString Task::parent() const
{
  return mParent;
}

void Task::setDueDate( const QDateTime& date )
{
  mDueDate = date;
  mHasDueDate = true;
}

QDateTime Task::dueDate() const
{
  return mDueDate;
}

void Task::setHasStartDate( bool v )
{
  mHasStartDate = v;
}

bool Task::hasStartDate() const
{
  return mHasStartDate;
}

bool Task::hasDueDate() const
{
  return mHasDueDate;
}

void Task::setCompletedDate( const QDateTime& date )
{
  mCompletedDate = date;
  mHasCompletedDate = true;
}

QDateTime Task::completedDate() const
{
  return mCompletedDate;
}

bool Task::hasCompletedDate() const
{
  return mHasCompletedDate;
}

bool Task::loadAttribute( QDomElement& element )
{
  QString tagName = element.tagName();

  if ( tagName == "priority" ) {
    bool ok;
    int priority = element.text().toInt( &ok );
    if ( !ok || priority < 0 || priority > 9 )
      priority = 5;
    setPriority( priority );
  } else if ( tagName == "completed" ) {
    bool ok;
    int percent = element.text().toInt( &ok );
    if ( !ok || percent < 0 || percent > 100 )
      percent = 0;
    setPercentCompleted( percent );
  } else if ( tagName == "status" ) {
    if ( element.text() == "in-progress" )
      setStatus( KCal::Incidence::StatusInProcess );
    else if ( element.text() == "completed" )
      setStatus( KCal::Incidence::StatusCompleted );
    else if ( element.text() == "waiting-on-someone-else" )
      setStatus( KCal::Incidence::StatusNeedsAction );
    else if ( element.text() == "deferred" )
      // Guessing a status here
      setStatus( KCal::Incidence::StatusCanceled );
    else
      // Default
      setStatus( KCal::Incidence::StatusNone );
  } else if ( tagName == "due-date" )
    setDueDate( stringToDateTime( element.text() ) );
  else if ( tagName == "parent" )
    setParent( element.text() );
  else if ( tagName == "x-completed-date" )
    setCompletedDate( stringToDateTime( element.text() ) );
  else if ( tagName == "start-date" ) {
    setHasStartDate( true );
    setStartDate( element.text() );
  } else
    return Incidence::loadAttribute( element );

  // We handled this
  return true;
}

bool Task::saveAttributes( QDomElement& element ) const
{
  // Save the base class elements
  Incidence::saveAttributes( element );

  writeString( element, "priority", QString::number( priority() ) );
  writeString( element, "completed", QString::number( percentCompleted() ) );

  switch( status() ) {
  case KCal::Incidence::StatusInProcess:
    writeString( element, "status", "in-progress" );
    break;
  case KCal::Incidence::StatusCompleted:
    writeString( element, "status", "completed" );
    break;
  case KCal::Incidence::StatusNeedsAction:
    writeString( element, "status", "waiting-on-someone-else" );
    break;
  case KCal::Incidence::StatusCanceled:
    writeString( element, "status", "deferred" );
    break;
  case KCal::Incidence::StatusNone:
    writeString( element, "status", "not-started" );
    break;
  case KCal::Incidence::StatusTentative:
  case KCal::Incidence::StatusConfirmed:
  case KCal::Incidence::StatusDraft:
  case KCal::Incidence::StatusFinal:
  case KCal::Incidence::StatusX:
    // All of these are saved as StatusNone.
    writeString( element, "status", "not-started" );
    break;
  }

  if ( hasDueDate() )
    writeString( element, "due-date", dateTimeToString( dueDate() ) );

  if ( !parent().isNull() )
    writeString( element, "parent", parent() );

  if ( hasCompletedDate() && percentCompleted() == 100)
    writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );

  return true;
}

bool Task::loadXML( const QDomDocument& document )
{
  QDomElement top = document.documentElement();

  if ( top.tagName() != "task" ) {
    qWarning( "XML error: Top tag was %s instead of the expected task",
              top.tagName().ascii() );
    return false;
  }
  setHasStartDate( false ); // todo's don't necessarily have one

  for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    if ( n.isComment() )
      continue;
    if ( n.isElement() ) {
      QDomElement e = n.toElement();
      if ( !loadAttribute( e ) )
        // TODO: Unhandled tag - save for later storage
        kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
    } else
      kdDebug() << "Node is not a comment or an element???" << endl;
  }

  return true;
}

QString Task::saveXML() const
{
  QDomDocument document = domTree();
  QDomElement element = document.createElement( "task" );
  element.setAttribute( "version", "1.0" );
  saveAttributes( element );
  if ( !hasStartDate() ) {
    // events and journals always have a start date, but tasks don't.
    // Remove the entry done by the inherited save above, because we
    // don't have one.
    QDomNodeList l = element.elementsByTagName( "start-date" );
    Q_ASSERT( l.count() == 1 );
    element.removeChild( l.item( 0 ) );
  }
  document.appendChild( element );
  return document.toString();
}

void Task::setFields( const KCal::Todo* task )
{
  Incidence::setFields( task );

  setPriority( task->priority() );
  setPercentCompleted( task->percentComplete() );
  setStatus( task->status() );
  setHasStartDate( task->hasStartDate() );

  if ( task->hasDueDate() )
    setDueDate( localToUTC( task->dtDue() ) );
  else
    mHasDueDate = false;
  if ( task->relatedTo() )
    setParent( task->relatedTo()->uid() );
  else
    setParent( QString::null );

  if ( task->hasCompletedDate() && task->percentComplete() == 100 )
    setCompletedDate( localToUTC( task->completed() ) );
  else
    mHasCompletedDate = false;
}

void Task::saveTo( KCal::Todo* task )
{
  Incidence::saveTo( task );

  task->setPriority( priority() );
  task->setPercentComplete( percentCompleted() );
  task->setStatus( status() );
  task->setHasStartDate( hasStartDate() );
  task->setHasDueDate( hasDueDate() );
  if ( hasDueDate() )
    task->setDtDue( utcToLocal( dueDate() ) );

  if ( !parent().isNull() )
    task->setRelatedToUid( parent() );

  if ( hasCompletedDate() && task->percentComplete() == 100 )
    task->setCompleted( utcToLocal( mCompletedDate ) );
}
<commit_msg>After long hours of tracking down the problem that the hierarchy of the to-do list was lost in the kolab resource, here's the fix. Every now and then korganizer's tasks would loose their parents, mostly when conflict resolution is triggered.<commit_after>/*
    This file is part of the kolab resource - the implementation of the
    Kolab storage format. See www.kolab.org for documentation on this.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "task.h"

#include <libkcal/todo.h>
#include <kdebug.h>

using namespace Kolab;

KCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )
{
  Task task( tz );
  task.load( xml );
  KCal::Todo* todo = new KCal::Todo();
  task.saveTo( todo );
  return todo;
}

QString Task::taskToXML( KCal::Todo* todo, const QString& tz )
{
  Task task( tz, todo );
  return task.saveXML();
}

Task::Task( const QString& tz, KCal::Todo* task )
  : Incidence( tz ), mPriority( 5 ), mPercentCompleted( 0 ),
    mStatus( KCal::Incidence::StatusNone ),
    mHasStartDate( false ), mHasDueDate( false ),
    mHasCompletedDate( false )
{
  if ( task )
    setFields( task );
}

Task::~Task()
{
}

void Task::setPriority( int priority )
{
  mPriority = priority;
}

int Task::priority() const
{
  return mPriority;
}

void Task::setPercentCompleted( int percent )
{
  mPercentCompleted = percent;
}

int Task::percentCompleted() const
{
  return mPercentCompleted;
}

void Task::setStatus( KCal::Incidence::Status status )
{
  mStatus = status;
}

KCal::Incidence::Status Task::status() const
{
  return mStatus;
}

void Task::setParent( const QString& parentUid )
{
  mParent = parentUid;
}

QString Task::parent() const
{
  return mParent;
}

void Task::setDueDate( const QDateTime& date )
{
  mDueDate = date;
  mHasDueDate = true;
}

QDateTime Task::dueDate() const
{
  return mDueDate;
}

void Task::setHasStartDate( bool v )
{
  mHasStartDate = v;
}

bool Task::hasStartDate() const
{
  return mHasStartDate;
}

bool Task::hasDueDate() const
{
  return mHasDueDate;
}

void Task::setCompletedDate( const QDateTime& date )
{
  mCompletedDate = date;
  mHasCompletedDate = true;
}

QDateTime Task::completedDate() const
{
  return mCompletedDate;
}

bool Task::hasCompletedDate() const
{
  return mHasCompletedDate;
}

bool Task::loadAttribute( QDomElement& element )
{
  QString tagName = element.tagName();

  if ( tagName == "priority" ) {
    bool ok;
    int priority = element.text().toInt( &ok );
    if ( !ok || priority < 0 || priority > 9 )
      priority = 5;
    setPriority( priority );
  } else if ( tagName == "completed" ) {
    bool ok;
    int percent = element.text().toInt( &ok );
    if ( !ok || percent < 0 || percent > 100 )
      percent = 0;
    setPercentCompleted( percent );
  } else if ( tagName == "status" ) {
    if ( element.text() == "in-progress" )
      setStatus( KCal::Incidence::StatusInProcess );
    else if ( element.text() == "completed" )
      setStatus( KCal::Incidence::StatusCompleted );
    else if ( element.text() == "waiting-on-someone-else" )
      setStatus( KCal::Incidence::StatusNeedsAction );
    else if ( element.text() == "deferred" )
      // Guessing a status here
      setStatus( KCal::Incidence::StatusCanceled );
    else
      // Default
      setStatus( KCal::Incidence::StatusNone );
  } else if ( tagName == "due-date" )
    setDueDate( stringToDateTime( element.text() ) );
  else if ( tagName == "parent" )
    setParent( element.text() );
  else if ( tagName == "x-completed-date" )
    setCompletedDate( stringToDateTime( element.text() ) );
  else if ( tagName == "start-date" ) {
    setHasStartDate( true );
    setStartDate( element.text() );
  } else
    return Incidence::loadAttribute( element );

  // We handled this
  return true;
}

bool Task::saveAttributes( QDomElement& element ) const
{
  // Save the base class elements
  Incidence::saveAttributes( element );

  writeString( element, "priority", QString::number( priority() ) );
  writeString( element, "completed", QString::number( percentCompleted() ) );

  switch( status() ) {
  case KCal::Incidence::StatusInProcess:
    writeString( element, "status", "in-progress" );
    break;
  case KCal::Incidence::StatusCompleted:
    writeString( element, "status", "completed" );
    break;
  case KCal::Incidence::StatusNeedsAction:
    writeString( element, "status", "waiting-on-someone-else" );
    break;
  case KCal::Incidence::StatusCanceled:
    writeString( element, "status", "deferred" );
    break;
  case KCal::Incidence::StatusNone:
    writeString( element, "status", "not-started" );
    break;
  case KCal::Incidence::StatusTentative:
  case KCal::Incidence::StatusConfirmed:
  case KCal::Incidence::StatusDraft:
  case KCal::Incidence::StatusFinal:
  case KCal::Incidence::StatusX:
    // All of these are saved as StatusNone.
    writeString( element, "status", "not-started" );
    break;
  }

  if ( hasDueDate() )
    writeString( element, "due-date", dateTimeToString( dueDate() ) );

  if ( !parent().isNull() )
    writeString( element, "parent", parent() );

  if ( hasCompletedDate() && percentCompleted() == 100)
    writeString( element, "x-completed-date", dateTimeToString( completedDate() ) );

  return true;
}

bool Task::loadXML( const QDomDocument& document )
{
  QDomElement top = document.documentElement();

  if ( top.tagName() != "task" ) {
    qWarning( "XML error: Top tag was %s instead of the expected task",
              top.tagName().ascii() );
    return false;
  }
  setHasStartDate( false ); // todo's don't necessarily have one

  for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {
    if ( n.isComment() )
      continue;
    if ( n.isElement() ) {
      QDomElement e = n.toElement();
      if ( !loadAttribute( e ) )
        // TODO: Unhandled tag - save for later storage
        kdDebug() << "Warning: Unhandled tag " << e.tagName() << endl;
    } else
      kdDebug() << "Node is not a comment or an element???" << endl;
  }

  return true;
}

QString Task::saveXML() const
{
  QDomDocument document = domTree();
  QDomElement element = document.createElement( "task" );
  element.setAttribute( "version", "1.0" );
  saveAttributes( element );
  if ( !hasStartDate() ) {
    // events and journals always have a start date, but tasks don't.
    // Remove the entry done by the inherited save above, because we
    // don't have one.
    QDomNodeList l = element.elementsByTagName( "start-date" );
    Q_ASSERT( l.count() == 1 );
    element.removeChild( l.item( 0 ) );
  }
  document.appendChild( element );
  return document.toString();
}

void Task::setFields( const KCal::Todo* task )
{
  Incidence::setFields( task );

  setPriority( task->priority() );
  setPercentCompleted( task->percentComplete() );
  setStatus( task->status() );
  setHasStartDate( task->hasStartDate() );

  if ( task->hasDueDate() )
    setDueDate( localToUTC( task->dtDue() ) );
  else
    mHasDueDate = false;
  if ( task->relatedTo() )
    setParent( task->relatedTo()->uid() );
  else if ( !task->relatedToUid().isEmpty() )
    setParent( task->relatedToUid() );
  else
    setParent( QString::null );

  if ( task->hasCompletedDate() && task->percentComplete() == 100 )
    setCompletedDate( localToUTC( task->completed() ) );
  else
    mHasCompletedDate = false;
}

void Task::saveTo( KCal::Todo* task )
{
  Incidence::saveTo( task );

  task->setPriority( priority() );
  task->setPercentComplete( percentCompleted() );
  task->setStatus( status() );
  task->setHasStartDate( hasStartDate() );
  task->setHasDueDate( hasDueDate() );
  if ( hasDueDate() )
    task->setDtDue( utcToLocal( dueDate() ) );

  if ( !parent().isNull() )
    task->setRelatedToUid( parent() );

  if ( hasCompletedDate() && task->percentComplete() == 100 )
    task->setCompleted( utcToLocal( mCompletedDate ) );
}
<|endoftext|>


<commit_before>/*
 * Copyright 2019 Benoy Bose
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "compiler/ParserDriver.hh"
#include "ast/Unit.hh"
#include "ast/Statement.hh"
#include "ast/ReferenceExpression.hh"
#include "ast/ArrayAccessExpression.hh"
#include "ast/LiteralExpression.hh"
#include "ast/BinaryExpression.hh"
#include "HoocTestHelper.hh"

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>

using namespace std;
using namespace hooc;
using namespace hooc::compiler;
using namespace hooc::ast;

BOOST_AUTO_TEST_SUITE(BinaryExpressionTest)

    BOOST_AUTO_TEST_CASE(BinaryExpression1) {
        const std::string source = "2 + 3;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;
        auto lvalue = binary_expr->GetLeftExpression();
        auto rvalue = binary_expr->GetRightExpression();
        auto opr = binary_expr->GetOperator();
        BOOST_CHECK_LITERAL_EXPRESSION(lvalue, LITERAL_INTEGER, "2");
        BOOST_CHECK_LITERAL_EXPRESSION(rvalue, LITERAL_INTEGER, "3");
        BOOST_CHECK_EQUAL(OPERATOR_ADD, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression2) {
        const std::string source = "a - b;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;
        auto lvalue = binary_expr->GetLeftExpression();
        auto rvalue = binary_expr->GetRightExpression();
        auto opr = binary_expr->GetOperator();
        BOOST_CHECK_REFERENCE_EXPRESSION(lvalue, "a");
        BOOST_CHECK_REFERENCE_EXPRESSION(rvalue, "b");
        BOOST_CHECK_EQUAL(OPERATOR_SUB, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression3) {
        const std::string source = "2 / 3 * 4;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;
        auto left_value = binary_expr->GetLeftExpression();
        auto right_value = binary_expr->GetRightExpression();
        auto opr = binary_expr->GetOperator();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_value->GetExpressionType());

        auto binary_expr_1 = (BinaryExpression*) left_value;
        auto binary_expr_1_left_value = binary_expr_1->GetLeftExpression();
        auto binary_expr_1_right_value = binary_expr_1->GetRightExpression();
        BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_left_value, LITERAL_INTEGER, "2");
        BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_right_value, LITERAL_INTEGER, "3");
        BOOST_CHECK_EQUAL(OPERATOR_DIV, binary_expr_1->GetOperator()->GetOperatorType());

        BOOST_CHECK_LITERAL_EXPRESSION(right_value, LITERAL_INTEGER, "4");
        BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression4) {
        const std::string source = "a / b * c % d;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;

        auto opr = binary_expr->GetOperator();
        auto left_expr = binary_expr->GetLeftExpression();
        auto right_expr = binary_expr->GetRightExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
        BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "d");
        BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());

        opr = ((BinaryExpression *) left_expr)->GetOperator();
        right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
        left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
        BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "c");
        BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());

        opr = ((BinaryExpression *) left_expr)->GetOperator();
        right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
        left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
        BOOST_CHECK_REFERENCE_EXPRESSION(left_expr, "a");
        BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "b");
        BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression5) {
        const std::string source = "(a / b) * (c % d);";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;

        auto opr = binary_expr->GetOperator();
        auto left_expr = binary_expr->GetLeftExpression();
        auto right_expr = binary_expr->GetRightExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, right_expr->GetExpressionType());
        BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());

        auto l1 = ((BinaryExpression *) left_expr)->GetLeftExpression();
        auto l2 = ((BinaryExpression *) left_expr)->GetRightExpression();
        opr = ((BinaryExpression *) left_expr)->GetOperator();

        BOOST_CHECK_REFERENCE_EXPRESSION(l1, "a");
        BOOST_CHECK_REFERENCE_EXPRESSION(l2, "b");
        BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());

        auto r1 = ((BinaryExpression *) right_expr)->GetLeftExpression();
        auto r2 = ((BinaryExpression *) right_expr)->GetRightExpression();
        opr = ((BinaryExpression *) right_expr)->GetOperator();

        BOOST_CHECK_REFERENCE_EXPRESSION(r1, "c");
        BOOST_CHECK_REFERENCE_EXPRESSION(r2, "d");
        BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());
    }

BOOST_AUTO_TEST_SUITE_END()<commit_msg>Tested equal comparison of array index access expressions.<commit_after>/*
 * Copyright 2019 Benoy Bose
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or
 * substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "compiler/ParserDriver.hh"
#include "ast/Unit.hh"
#include "ast/Statement.hh"
#include "ast/ReferenceExpression.hh"
#include "ast/ArrayAccessExpression.hh"
#include "ast/LiteralExpression.hh"
#include "ast/BinaryExpression.hh"
#include "HoocTestHelper.hh"

#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>

using namespace std;
using namespace hooc;
using namespace hooc::compiler;
using namespace hooc::ast;

BOOST_AUTO_TEST_SUITE(BinaryExpressionTest)

    BOOST_AUTO_TEST_CASE(BinaryExpression1) {
        const std::string source = "2 + 3;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;
        auto lvalue = binary_expr->GetLeftExpression();
        auto rvalue = binary_expr->GetRightExpression();
        auto opr = binary_expr->GetOperator();
        BOOST_CHECK_LITERAL_EXPRESSION(lvalue, LITERAL_INTEGER, "2");
        BOOST_CHECK_LITERAL_EXPRESSION(rvalue, LITERAL_INTEGER, "3");
        BOOST_CHECK_EQUAL(OPERATOR_ADD, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression2) {
        const std::string source = "a - b;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;
        auto lvalue = binary_expr->GetLeftExpression();
        auto rvalue = binary_expr->GetRightExpression();
        auto opr = binary_expr->GetOperator();
        BOOST_CHECK_REFERENCE_EXPRESSION(lvalue, "a");
        BOOST_CHECK_REFERENCE_EXPRESSION(rvalue, "b");
        BOOST_CHECK_EQUAL(OPERATOR_SUB, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression3) {
        const std::string source = "2 / 3 * 4;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;
        auto left_value = binary_expr->GetLeftExpression();
        auto right_value = binary_expr->GetRightExpression();
        auto opr = binary_expr->GetOperator();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_value->GetExpressionType());

        auto binary_expr_1 = (BinaryExpression*) left_value;
        auto binary_expr_1_left_value = binary_expr_1->GetLeftExpression();
        auto binary_expr_1_right_value = binary_expr_1->GetRightExpression();
        BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_left_value, LITERAL_INTEGER, "2");
        BOOST_CHECK_LITERAL_EXPRESSION(binary_expr_1_right_value, LITERAL_INTEGER, "3");
        BOOST_CHECK_EQUAL(OPERATOR_DIV, binary_expr_1->GetOperator()->GetOperatorType());

        BOOST_CHECK_LITERAL_EXPRESSION(right_value, LITERAL_INTEGER, "4");
        BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression4) {
        const std::string source = "a / b * c % d;";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;

        auto opr = binary_expr->GetOperator();
        auto left_expr = binary_expr->GetLeftExpression();
        auto right_expr = binary_expr->GetRightExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
        BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "d");
        BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());

        opr = ((BinaryExpression *) left_expr)->GetOperator();
        right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
        left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
        BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "c");
        BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());

        opr = ((BinaryExpression *) left_expr)->GetOperator();
        right_expr = ((BinaryExpression *) left_expr)->GetRightExpression();
        left_expr = ((BinaryExpression *) left_expr)->GetLeftExpression();
        BOOST_CHECK_REFERENCE_EXPRESSION(left_expr, "a");
        BOOST_CHECK_REFERENCE_EXPRESSION(right_expr, "b");
        BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression5) {
        const std::string source = "(a / b) * (c % d);";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;

        auto opr = binary_expr->GetOperator();
        auto left_expr = binary_expr->GetLeftExpression();
        auto right_expr = binary_expr->GetRightExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, left_expr->GetExpressionType());
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, right_expr->GetExpressionType());
        BOOST_CHECK_EQUAL(OPERATOR_MUL, opr->GetOperatorType());

        auto l1 = ((BinaryExpression *) left_expr)->GetLeftExpression();
        auto l2 = ((BinaryExpression *) left_expr)->GetRightExpression();
        opr = ((BinaryExpression *) left_expr)->GetOperator();

        BOOST_CHECK_REFERENCE_EXPRESSION(l1, "a");
        BOOST_CHECK_REFERENCE_EXPRESSION(l2, "b");
        BOOST_CHECK_EQUAL(OPERATOR_DIV, opr->GetOperatorType());

        auto r1 = ((BinaryExpression *) right_expr)->GetLeftExpression();
        auto r2 = ((BinaryExpression *) right_expr)->GetRightExpression();
        opr = ((BinaryExpression *) right_expr)->GetOperator();

        BOOST_CHECK_REFERENCE_EXPRESSION(r1, "c");
        BOOST_CHECK_REFERENCE_EXPRESSION(r2, "d");
        BOOST_CHECK_EQUAL(OPERATOR_MOD, opr->GetOperatorType());
    }

    BOOST_AUTO_TEST_CASE(BinaryExpression6) {
        const std::string source = "a[0] == b[1];";
        ParserDriver driver(source, "test.hoo");
        auto module = driver.BuildModule();
        BOOST_CHECK(module->Success());
        auto unit = module->GetUnit();
        auto unit_items = unit->GetItems();
        BOOST_CHECK_EQUAL(1, unit_items.size());
        auto unit_item = *(unit_items.begin());
        BOOST_CHECK_EQUAL(UNIT_ITEM_STATEMENT, unit_item->GetUnitItemType());
        auto stmt = (Statement *) unit_item;
        BOOST_CHECK_EQUAL(STMT_EXPRESSION, stmt->GetStatementType());
        auto expr = ((ExpressionStatement *) unit_item)->GetExpression();
        BOOST_CHECK_EQUAL(EXPRESSION_BINARY, expr->GetExpressionType());
        auto binary_expr = (BinaryExpression *) expr;

        auto opr = binary_expr->GetOperator();
        auto left_expr = binary_expr->GetLeftExpression();
        auto right_expr = binary_expr->GetRightExpression();

        BOOST_CHECK_EQUAL(OPERATOR_EQUAL, opr->GetOperatorType());
        auto a_array = (ArrayAccessExpression *) left_expr;
        auto b_array = (ArrayAccessExpression *) right_expr;
        auto a = a_array->GetContainer();
        auto index0 = a_array->GetIndex();
        BOOST_CHECK_REFERENCE_EXPRESSION(a, "a");
        BOOST_CHECK_LITERAL_EXPRESSION(index0, LITERAL_INTEGER, "0");
        auto b = b_array->GetContainer();
        auto index1 = b_array->GetIndex();
        BOOST_CHECK_REFERENCE_EXPRESSION(b, "b");
        BOOST_CHECK_LITERAL_EXPRESSION(index1, LITERAL_INTEGER, "1");
    }

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before><commit_msg>make style<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2015 Pavel Novy. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "rfl-scan/compilation_db.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_os_ostream.h"

namespace rfl {
namespace scan {

ScanCompilationDatabase::ScanCompilationDatabase(
    CompilationDatabase &cdb,
    std::vector<std::string> sources) : compilation_db_(cdb), source_files_(sources){
}

ScanCompilationDatabase::~ScanCompilationDatabase() {
}

char const *const kHeaderExtensions[] = {".h", ".hh", ".hpp", ".h++"};
char const *const kSourceExtensions[] = {".cc", ".cpp", ".cxx", ".c++", ".c"};

void ScanCompilationDatabase::cleanupCommands(std::vector<CompileCommand> &cmds,
                                              StringRef const &filename) const {
  // go through all commandlines and replace -c file with ours
  for (CompileCommand &cmd : cmds) {

    for (std::vector<std::string>::iterator it = cmd.CommandLine.begin();
         it != cmd.CommandLine.end();) {
      if (!it->empty() && it->compare("-c") == 0) {
        ++it;
        it->assign(filename);
      } else {
        ++it;
      }
    }
    // since this is header we need to specify that's a c++ header
    cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "c++");
    cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "-x");
  }
}

std::vector<CompileCommand> ScanCompilationDatabase::getCompileCommands(
    StringRef file) const {
  std::vector<CompileCommand> result = compilation_db_.getCompileCommands(file);
  if (result.empty()) {
    // check whether this is a header, if so, try to find .cc file
    StringRef ext = sys::path::extension(file);
    ArrayRef<char const *> hdr_exts(kHeaderExtensions);
    ArrayRef<char const *> src_exts(kSourceExtensions);
    for (ArrayRef<char const *>::const_iterator it = hdr_exts.begin();
         it != hdr_exts.end();
         ++it) {
      if (ext.compare(*it) == 0) {
        // header extensions match, so try to replace it with source ext.
        for (ArrayRef<char const *>::const_iterator cit = src_exts.begin();
             cit != src_exts.end();
             ++cit) {
          SmallString<1024> src_file(file);
          sys::path::replace_extension(src_file, *cit);
          result = compilation_db_.getCompileCommands(src_file);
          if (result.size()) {
            cleanupCommands(result,file);
            return result;
          }
        }
        break;
      }
    }

    outs() << "No luck for: " << file << "\n";
    outs().flush();

    // Nothing found, try all other files
    for (std::string const &src : source_files_) {
      if (src.compare(file) == 0)
        continue;
      result = getCompileCommands(src);
      if (!result.empty())
        cleanupCommands(result,file);
        return result;
    }
  }
  return result;
}

std::vector<std::string> ScanCompilationDatabase::getAllFiles() const {
  return source_files_;
}

std::vector<CompileCommand> ScanCompilationDatabase::getAllCompileCommands() const {
  std::vector<CompileCommand> cmds;
  for (std::string const &source : source_files_) {
    std::vector<CompileCommand> source_cmds =
        compilation_db_.getCompileCommands(source);
    if (!source_cmds.empty())
      cmds.insert(cmds.end(), source_cmds.begin(), source_cmds.end());
  }
  return cmds;
}

} // namespace scan
} // namespace rfl
<commit_msg>CompilationDB cleanup, Fix -gsplit-dwarf creating more then one compilation job<commit_after>// Copyright (c) 2015 Pavel Novy. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "rfl-scan/compilation_db.h"

#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_os_ostream.h"

namespace rfl {
namespace scan {

ScanCompilationDatabase::ScanCompilationDatabase(
    CompilationDatabase &cdb,
    std::vector<std::string> sources) : compilation_db_(cdb), source_files_(sources){
}

ScanCompilationDatabase::~ScanCompilationDatabase() {
}

char const *const kHeaderExtensions[] = {".h", ".hh", ".hpp", ".h++"};
char const *const kSourceExtensions[] = {".cc", ".cpp", ".cxx", ".c++", ".c"};

void ScanCompilationDatabase::cleanupCommands(std::vector<CompileCommand> &cmds,
                                              StringRef const &filename) const {
  // go through all commandlines and replace -c file with ours
  for (CompileCommand &cmd : cmds) {
    for (std::vector<std::string>::iterator it = cmd.CommandLine.begin();
         it != cmd.CommandLine.end();) {
      if (!it->empty() && it->compare("-c") == 0) {
        ++it;
        it->assign(filename);
      } else if (it->compare("-gsplit-dwarf") == 0) {
        it = cmd.CommandLine.erase(it);
      }
      else {
        ++it;
      }
    }
    // since this is header we need to specify that's a c++ header
    cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "c++");
    cmd.CommandLine.insert(cmd.CommandLine.begin() + 1, "-x");
  }
}

std::vector<CompileCommand> ScanCompilationDatabase::getCompileCommands(
    StringRef file) const {
  std::vector<CompileCommand> result = compilation_db_.getCompileCommands(file);
  if (!result.empty())
    return result;

  // check whether this is a header, if so, try to find .cc file
  StringRef ext = sys::path::extension(file);
  ArrayRef<char const *> hdr_exts(kHeaderExtensions);
  ArrayRef<char const *> src_exts(kSourceExtensions);
  for (ArrayRef<char const *>::const_iterator it = hdr_exts.begin();
       it != hdr_exts.end();
       ++it) {
    if (ext.compare(*it) == 0) {
      // header extensions match, so try to replace it with source ext.
      for (ArrayRef<char const *>::const_iterator cit = src_exts.begin();
           cit != src_exts.end();
           ++cit) {
        SmallString<1024> src_file(file);
        sys::path::replace_extension(src_file, *cit);
        result = compilation_db_.getCompileCommands(src_file);
        if (result.size()) {
          cleanupCommands(result,file);
          return result;
        }
      }
      break;
    }
  }

  outs() << "No luck for: " << file << "\n";
  outs().flush();

  // Nothing found, try all other files
  for (std::string const &src : source_files_) {
    if (src.compare(file) == 0)
      continue;
    result = getCompileCommands(src);
    if (!result.empty())
      cleanupCommands(result,file);
      return result;
  }
  return result;
}

std::vector<std::string> ScanCompilationDatabase::getAllFiles() const {
  return source_files_;
}

std::vector<CompileCommand> ScanCompilationDatabase::getAllCompileCommands() const {
  std::vector<CompileCommand> cmds;
  for (std::string const &source : source_files_) {
    std::vector<CompileCommand> source_cmds =
        compilation_db_.getCompileCommands(source);
    if (!source_cmds.empty())
      cmds.insert(cmds.end(), source_cmds.begin(), source_cmds.end());
  }
  return cmds;
}

} // namespace scan
} // namespace rfl
<|endoftext|>